diff --git a/agent-notes/perf-visual-render.md b/agent-notes/perf-visual-render.md new file mode 100644 index 00000000..deecc503 --- /dev/null +++ b/agent-notes/perf-visual-render.md @@ -0,0 +1,24 @@ +# Goal + +Optimize the live Three.js room view and open a pull request against master. + +## State + +Implemented the shared animation frame after Q approved. Joint motion advances before drawing, the last drawn room's resources survive until its replacement draws, and each visible label uses one keyed lookup. + +## Decisions and why + +- `RoomLayout3D.tsx:241` draws synchronously on OrbitControls change. Wheel zoom updates controls then draws explicitly at lines 544–545. Coalesce visual changes into one pending animation frame. Keep input state updates immediate and use the latest camera, room, labels and selection when drawing. +- Audit first paint, resize, orbit, wheel, touch, keyboard, camera modes, layout, bodies, selection and bake completion as frame producers. Advance joint animation before drawing so the final pose appears and animation does not trail input by a frame. Cancel pending work on teardown. +- `RoomLayout3D.tsx:421` depends on drawing replacement materials before disposing the prior room. Preserve that lifetime across deferred and superseded frames and unmount. +- `placeVisibleLabels` searches the entire request list for each placed label. Reuse the per-id lookup already needed for projected anchors to avoid repeated scans while preserving label selection, priority and hit regions. + +## Surprises + +The lighting bake uses its own frame budget and signals completion. The preview has its own explicit rendering contract. A five-event wheel burst in the live component with the sample layout at 480 by 320 in headless Edge produced ten composer draws on master and one after this change. Synchronous composer draws fell from ten to zero. The regression test independently reproduced ten before the change. + +## Next step + +The regression covers the wheel burst, idle, bake completion, teardown and replacement before painting. Publish the branch and open the PR, then follow CI. + +Reference: https://threejs.org/manual/pages/rendering-on-demand.html diff --git a/src/components/RoomLayout3D.test.tsx b/src/components/RoomLayout3D.test.tsx new file mode 100644 index 00000000..eac8df40 --- /dev/null +++ b/src/components/RoomLayout3D.test.tsx @@ -0,0 +1,76 @@ +import { fireEvent, render } from "@testing-library/react"; +import { afterEach, expect, it, vi } from "vitest"; +import { sampleLayout } from "../map/roomLayout.fixture"; +import * as roomScene from "../map/roomScene"; +import RoomLayout3D from "./RoomLayout3D"; + +const draw = vi.hoisted(() => vi.fn()); +let finishBake: () => void; +vi.mock("../map/roomRenderer", () => ({ + roomRenderer: () => ({ + renderer: { domElement: document.createElement("canvas"), setSize: vi.fn(), shadowMap: {} }, + dispose: vi.fn(), + }), +})); +vi.mock("../map/roomPost", () => ({ + roomPost: () => ({ setRoom: vi.fn(), setSize: vi.fn(), render: draw, dispose: vi.fn() }), +})); +vi.mock("../map/roomBounce", () => ({ + lightRoom: () => ({ baked: new Promise((resolve) => { finishBake = resolve; }), dispose: vi.fn() }), +})); + +afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllGlobals(); +}); + +it("combines wheel events into one room draw and cancels the last request on unmount", async () => { + vi.spyOn(HTMLElement.prototype, "clientWidth", "get").mockReturnValue(480); + vi.spyOn(HTMLElement.prototype, "clientHeight", "get").mockReturnValue(320); + vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue({} as WebGL2RenderingContext); + const pending = new Map(); + let id = 0; + vi.stubGlobal("requestAnimationFrame", (step: FrameRequestCallback) => { + pending.set(++id, step); + return id; + }); + vi.stubGlobal("cancelAnimationFrame", (handle: number) => pending.delete(handle)); + const paint = () => { + const callbacks = [...pending.values()]; + pending.clear(); + for (const callback of callbacks) callback(100); + }; + const layout = { ...sampleLayout(), things: [] }; + const picture = (size: typeof layout.size) => ; + const dispose = vi.spyOn(roomScene, "disposeRoomScene"); + const view = render(picture(layout.size)); + paint(); + expect(draw).toHaveBeenCalledTimes(1); + draw.mockClear(); + const room = view.getByRole("img"); + for (let i = 0; i < 5; i++) fireEvent.wheel(room, { deltaY: -20 }); + expect(draw).not.toHaveBeenCalled(); + expect(pending.size).toBe(1); + paint(); + expect(draw).toHaveBeenCalledTimes(1); + expect(pending.size).toBe(0); + finishBake(); + await Promise.resolve(); + expect(pending.size).toBe(1); + paint(); + expect(draw).toHaveBeenCalledTimes(2); + view.rerender(picture([8, 8, 3])); + expect(dispose).not.toHaveBeenCalled(); + view.rerender(picture([9, 8, 3])); + expect(dispose).toHaveBeenCalledTimes(1); + paint(); + expect(dispose).toHaveBeenCalledTimes(2); + fireEvent.keyDown(room, { key: "ArrowLeft" }); + expect(pending.size).toBe(1); + view.unmount(); + expect(dispose).toHaveBeenCalledTimes(3); + finishBake(); + await Promise.resolve(); + expect(pending.size).toBe(0); +}); diff --git a/src/components/RoomLayout3D.tsx b/src/components/RoomLayout3D.tsx index 637e29d0..a7815a0e 100644 --- a/src/components/RoomLayout3D.tsx +++ b/src/components/RoomLayout3D.tsx @@ -117,8 +117,9 @@ interface Stage { controls: OrbitControls; scene: THREE.Scene; room: RoomScene | null; - /** Stops the jointed parts' swing or slide where it is. */ - stopJoints: () => void; + stepJoints: ReturnType; + /** Keep its materials alive until the replacement has drawn with the shared shaders. */ + lastDrawn: RoomScene | null; layout: RoomLayout | null; placed: PlacedThing[]; /** People's figure geometries, reused while their look is unchanged. */ @@ -134,7 +135,7 @@ interface Stage { personLabels: Array; /** The outline round the selected thing or person, when it is drawn. */ selection: THREE.Group | null; - render: () => void; + requestDraw: () => void; } /** @@ -147,7 +148,7 @@ function lightStage(stage: Stage, room: RoomScene, layout: RoomLayout) { stage.light?.dispose(); const light = lightRoom(stage.renderer, stage.scene, room, layout, () => (stage.selection ? [stage.selection] : [])); stage.light = light; - void light.baked.then(() => { if (stage.light === light) stage.render(); }); + void light.baked.then(() => { if (stage.light === light) stage.requestDraw(); }); } /** Outlines the selected thing or person where it now is, marks its label, and clears the last outline. */ @@ -209,6 +210,26 @@ const RoomLayout3D: React.FC = ({ layout, placed, youId, labe // (`onWheel` below takes it), and two fingers are left to `onTouchPointer`, which zooms the same way. controls.touches.TWO = null; const scene = new THREE.Scene(); + let pending: number | null = null; + let width = 0; + let height = 0; + function draw(time: number) { + pending = null; + if (!stage.room || !stage.layout || !width || !height) return; + if (stage.stepJoints) { + renderer.shadowMap.needsUpdate = true; + if (stage.stepJoints(time)) stage.requestDraw(); + else stage.stepJoints = null; + } + camera.updateMatrixWorld(); + cutWalls(stage.room, stage.layout, camera.position, modeRef.current); + updateTinyMarkers(stage.room, camera, width, height, modeRef.current); + stage.post.render(); + placeVisibleLabels(stage, width, height); + labels.render(scene, camera); + if (stage.lastDrawn && stage.lastDrawn !== stage.room) disposeRoomScene(stage.lastDrawn); + stage.lastDrawn = stage.room; + } const stage: Stage = { renderer, @@ -217,7 +238,8 @@ const RoomLayout3D: React.FC = ({ layout, placed, youId, labe controls, scene, room: null, - stopJoints: () => {}, + stepJoints: null, + lastDrawn: null, layout: null, placed: [], figures: new FigureCache(), @@ -227,22 +249,19 @@ const RoomLayout3D: React.FC = ({ layout, placed, youId, labe labelSizes: new Map(), personLabels: [], selection: null, - render: () => { - if (stage.room) { - cutWalls(stage.room, layoutRef.current, camera.position, modeRef.current); - updateTinyMarkers(stage.room, camera, frame.clientWidth, frame.clientHeight, modeRef.current); - } - stage.post.render(); - placeVisibleLabels(stage); - labels.render(scene, camera); + requestDraw: () => { + if (pending === null) pending = requestAnimationFrame(draw); }, }; stageRef.current = stage; - controls.addEventListener("change", stage.render); + controls.addEventListener("change", stage.requestDraw); const resize = () => { - const width = frame.clientWidth; - const height = frame.clientHeight; + const nextWidth = frame.clientWidth; + const nextHeight = frame.clientHeight; + if (width === nextWidth && height === nextHeight) return; + width = nextWidth; + height = nextHeight; if (width === 0 || height === 0) return; renderer.setSize(width, height, false); stage.post.setSize(width, height); @@ -251,10 +270,11 @@ const RoomLayout3D: React.FC = ({ layout, placed, youId, labe labels.setSize(width, height); camera.aspect = width / height; camera.updateProjectionMatrix(); - stage.render(); + stage.requestDraw(); }; const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(resize); - observer?.observe(frame); + if (observer) observer.observe(frame); + else window.addEventListener("resize", resize); resize(); // Taken on the way down to the canvas, so the orbit controls' own wheel zoom never runs. const wheel = (event: WheelEvent) => onWheelRef.current(event); @@ -263,13 +283,16 @@ const RoomLayout3D: React.FC = ({ layout, placed, youId, labe return () => { frame.removeEventListener("wheel", wheel, { capture: true }); observer?.disconnect(); - controls.removeEventListener("change", stage.render); + if (!observer) window.removeEventListener("resize", resize); + controls.removeEventListener("change", stage.requestDraw); + if (pending !== null) cancelAnimationFrame(pending); controls.dispose(); - stage.stopJoints(); + if (stage.lastDrawn && stage.lastDrawn !== stage.room) disposeRoomScene(stage.lastDrawn); if (stage.selection) disposeSelectionOutline(stage.selection); if (stage.room) disposeRoomScene(stage.room); stage.figures.dispose(); stage.light?.dispose(); + stage.light = null; stage.post.dispose(); disposeRenderer(); renderer.domElement.remove(); @@ -278,18 +301,13 @@ const RoomLayout3D: React.FC = ({ layout, placed, youId, labe }; }, [supported]); - const layoutRef = useRef(layout); - layoutRef.current = layout; - /** Shows the labels that fit, most important first, each just above its head or thing; hides the rest. */ - function placeVisibleLabels(stage: Stage) { - const width = stage.labels.domElement.clientWidth || stage.renderer.domElement.clientWidth; - const height = stage.labels.domElement.clientHeight || stage.renderer.domElement.clientHeight; + function placeVisibleLabels(stage: Stage, width: number, height: number) { const requests: LabelOver[] = []; - const anchors = new Map(); + const anchors = new Map(); const projected = new THREE.Vector3(); // The selected thing's or person's label first, so it always shows where there is any room for it. - for (const { id, text } of selectedFirst(labelPlan.current, selectedIdRef.current)) { + for (const { id, text, person } of selectedFirst(labelPlan.current, selectedIdRef.current)) { const points = stage.room?.labelPoints.get(id); const object = stage.labelObjects.get(id); if (!points || !object) continue; @@ -299,12 +317,12 @@ const RoomLayout3D: React.FC = ({ layout, placed, youId, labe if (!shown) continue; // Where CSS2DRenderer puts the label before it is moved: its object's point. object.getWorldPosition(projected).project(stage.camera); - anchors.set(id, [((projected.x + 1) / 2) * width, ((1 - projected.y) / 2) * height]); const drawnSize = labelSize(object.element, stage.labelSizes); if (drawnSize.width === 0) continue; // The selected label's dashed box (`.rl3d-label-selected`) stands SELECTED_LABEL_RING px outside its text on every side. const ring = id === selectedIdRef.current ? SELECTED_LABEL_RING * 2 : 0; const size = { width: drawnSize.width + ring, height: drawnSize.height + ring }; + anchors.set(id, { x: ((projected.x + 1) / 2) * width, y: ((1 - projected.y) / 2) * height, ...size, person }); // Centred over the head (or thing), its bottom edge LABEL_GAP pixels above the head's top as drawn: clear of hair and face at any zoom. requests.push({ id, text, x: shown.x, top: shown.top, ...size }); } @@ -317,22 +335,20 @@ const RoomLayout3D: React.FC = ({ layout, placed, youId, labe } const inset = 4; const placedLabels = placeLabelsOver(requests, LABEL_GAP, { x0: inset, x1: width - inset, y0: inset, y1: height - inset }, heads); - const people = new Set(labelPlan.current.filter((p) => p.person).map((p) => p.id)); stage.personLabels = []; for (const placedLabel of placedLabels) { const object = stage.labelObjects.get(placedLabel.id); const anchor = anchors.get(placedLabel.id); if (!object || !anchor) continue; object.visible = true; - object.element.style.translate = `${placedLabel.x - anchor[0]}px ${placedLabel.y - anchor[1]}px`; - const size = requests.find((r) => r.id === placedLabel.id); - if (size && people.has(placedLabel.id)) { + object.element.style.translate = `${placedLabel.x - anchor.x}px ${placedLabel.y - anchor.y}px`; + if (anchor.person) { stage.personLabels.push({ id: placedLabel.id, - x0: placedLabel.x - size.width / 2, - x1: placedLabel.x + size.width / 2, - y0: placedLabel.y - size.height / 2, - y1: placedLabel.y + size.height / 2, + x0: placedLabel.x - anchor.width / 2, + x1: placedLabel.x + anchor.width / 2, + y0: placedLabel.y - anchor.height / 2, + y1: placedLabel.y + anchor.height / 2, }); } } @@ -355,7 +371,7 @@ const RoomLayout3D: React.FC = ({ layout, placed, youId, labe if (you) you.visible = mode !== "eyes"; showSelection(stage, selectedIdRef.current); stage.renderer.shadowMap.needsUpdate = true; - stage.render(); + stage.requestDraw(); return; } const previous = stage.room; @@ -364,7 +380,6 @@ const RoomLayout3D: React.FC = ({ layout, placed, youId, labe stage.labelObjects.clear(); // A door or drawer that moved swings or slides there from where it was drawn, unless motion is reduced. - stage.stopJoints(); const drawnJoints = previous ? jointPositions(previous) : new Map(); const room = buildRoomScene({ layout, placed, youId, figures: stage.figures }); stage.room = room; @@ -410,18 +425,11 @@ const RoomLayout3D: React.FC = ({ layout, placed, youId, labe } showSelection(stage, selectedIdRef.current); // Set before the first frame, so a moving part is first drawn where it was. - const moved = () => { - stage.renderer.shadowMap.needsUpdate = true; - stage.render(); - }; - stage.stopJoints = animateJoints(room, drawnJoints, moved, + stage.stepJoints = animateJoints(room, drawnJoints, jointSwingMs(typeof window.matchMedia === "function" ? (query) => window.matchMedia(query) : undefined)); - moved(); - // Free the previous room only once the new one is drawn. three.js shares a - // compiled shader between materials alike and deletes it when the last one is - // disposed; disposing first made it recompile every shader on every rebuild, - // which is every frame while anyone moves. - if (previous) disposeRoomScene(previous); + stage.renderer.shadowMap.needsUpdate = true; + stage.requestDraw(); + if (previous && previous !== stage.lastDrawn) disposeRoomScene(previous); }, [layout, placed, youId, mode]); // The selection changed (in a list, in this picture, by interact mode): outline it. Nothing else moves. @@ -429,7 +437,7 @@ const RoomLayout3D: React.FC = ({ layout, placed, youId, labe const stage = stageRef.current; if (!stage) return; showSelection(stage, selectedId); - stage.render(); + stage.requestDraw(); }, [selectedId]); // A new room or a new view starts the dollhouse at its whole-room view. @@ -447,7 +455,7 @@ const RoomLayout3D: React.FC = ({ layout, placed, youId, labe stage.controls.maxDistance = dollhouseMaxDistance(layout); applyPose(stage, dollhousePose(layout)); stage.controls.update(); - stage.render(); + stage.requestDraw(); } }, [mode, layout.num]); @@ -458,7 +466,7 @@ const RoomLayout3D: React.FC = ({ layout, placed, youId, labe const position = listenerPosition ? webAudioToMongooseVector(listenerPosition) : null; const forward = listenerForward ? webAudioToMongooseVector(listenerForward) : null; applyPose(stage, eyesPose(layout, position, forward, youBounds)); - stage.render(); + stage.requestDraw(); }, [mode, layout, listenerPosition, listenerForward, youBounds?.x0, youBounds?.y0, youBounds?.z1]); // A click selects the thing or person under it, presses a part or drawer, or sends a doorway's @@ -496,7 +504,7 @@ const RoomLayout3D: React.FC = ({ layout, placed, youId, labe if (!stage || fov === undefined) return false; stage.camera.fov = fov; stage.camera.updateProjectionMatrix(); - stage.render(); + stage.requestDraw(); return true; }; @@ -515,7 +523,7 @@ const RoomLayout3D: React.FC = ({ layout, placed, youId, labe if (mode === "eyes") { stage.camera.fov = zoomedFovBy(stage.camera.fov, notches); stage.camera.updateProjectionMatrix(); - stage.render(); + stage.requestDraw(); return; } zoomOnto(stage, event.clientX, event.clientY, wheelStep(layout) ** notches); @@ -542,7 +550,7 @@ const RoomLayout3D: React.FC = ({ layout, placed, youId, labe // A small animal form frames nearer than ZOOM_NEAREST; the orbit keeps the camera that near when the keys turn it. stage.controls.minDistance = orbitNearest(pick); stage.controls.update(); - stage.render(); + stage.requestDraw(); }; // Two fingers zoom like the wheel, onto what is under the point where the pinch began. @@ -600,7 +608,7 @@ const RoomLayout3D: React.FC = ({ layout, placed, youId, labe if (!action) return; event.preventDefault(); action(); - stage.render(); + stage.requestDraw(); }; if (!supported) { diff --git a/src/map/roomScene.test.ts b/src/map/roomScene.test.ts index a3d1df8c..7e4892ed 100644 --- a/src/map/roomScene.test.ts +++ b/src/map/roomScene.test.ts @@ -552,25 +552,20 @@ describe("buildRoomScene", () => { expect(box(drawer).min.y).toBeCloseTo(-0.75); expect(clickAlong(open, [-0.25, -0.7, 2.4], [-0.25, -0.7, 0])).toEqual({ kind: "fitting", lifetime: "drawer-life" }); // Rebuilt for the open layout, it starts where the closed one was drawn and eases there. - const steps: Array<(time: number) => void> = []; - let frames = 0; - const stop = animateJoints(open, jointPositions(closed), () => { frames++; }, 200, (step) => steps.push(step), () => {}); + const step = animateJoints(open, jointPositions(closed), 200); expect(box(drawer).min.y).toBeCloseTo(-0.45); - steps.shift()?.(1000); - steps.shift()?.(1100); + expect(step?.(1000)).toBe(true); + expect(step?.(1100)).toBe(true); expect(box(drawer).min.y).toBeCloseTo(-0.6); - steps.shift()?.(1200); + expect(step?.(1200)).toBe(false); expect(box(drawer).min.y).toBeCloseTo(-0.75); - expect(steps).toHaveLength(0); - expect(frames).toBe(3); - stop(); // Reduced motion, as RoomLayout3D asks it: no swing, no frame scheduled, the part drawn at once at its new pose. const reduced = (query: string) => ({ matches: query === "(prefers-reduced-motion: reduce)" }); expect(jointSwingMs(reduced)).toBe(0); expect(jointSwingMs(() => ({ matches: false }))).toBe(JOINT_ANIMATION_MS); expect(jointSwingMs(undefined)).toBe(JOINT_ANIMATION_MS); const again = build(withParts(Math.PI / 2, 0.3)); - animateJoints(again, jointPositions(closed), () => {}, jointSwingMs(reduced), () => { throw new Error("scheduled a frame"); }); + expect(animateJoints(again, jointPositions(closed), jointSwingMs(reduced))).toBeNull(); expect(box(meshes(again.things.get("#cab"))[1]).min.y).toBeCloseTo(-0.75); for (const scene of [closed, open, again]) disposeRoomScene(scene); }); diff --git a/src/map/roomScene.ts b/src/map/roomScene.ts index 62dcfd7e..64b1875d 100644 --- a/src/map/roomScene.ts +++ b/src/map/roomScene.ts @@ -89,28 +89,25 @@ export function jointPositions(room: RoomScene): Map { /** * Swings or slides each jointed part of `room` from where it was drawn before (`before`, from `jointPositions`) - * to its position now over `duration` ms, calling `render` each frame. Returns a function that stops it there. + * to its position now over `duration` ms. Step before drawing; true asks for another frame. * Parts that were not drawn before, or have not moved, stay put; a zero duration moves nothing. */ export function animateJoints( room: RoomScene, before: Map, - render: () => void, duration = JOINT_ANIMATION_MS, - frame: (step: (time: number) => void) => number = requestAnimationFrame, - cancel: (id: number) => void = cancelAnimationFrame, -): () => void { +): ((time: number) => boolean) | null { + if (!before.size || duration <= 0) return null; const moving: Array<{ mesh: THREE.Mesh; part: LayoutFormPart; from: number; to: number }> = []; room.root.traverse((object) => { const joint = object.userData.joint as { key: string; part: LayoutFormPart } | undefined; const from = joint && before.get(joint.key); - if (!joint || from === undefined || duration <= 0 || !(object instanceof THREE.Mesh)) return; + if (!joint || from === undefined || !(object instanceof THREE.Mesh)) return; const to = joint.part.joint?.position ?? 0; if (from !== to) moving.push({ mesh: object, part: joint.part, from, to }); }); - if (!moving.length) return () => {}; + if (!moving.length) return null; let start: number | undefined; - let id = 0; const step = (time: number) => { start ??= time; const t = Math.min(1, (time - start) / duration); @@ -120,15 +117,13 @@ export function animateJoints( placePart(mesh, part, from + (to - from) * eased); mesh.updateMatrixWorld(true); } - render(); - if (t < 1) id = frame(step); + return t < 1; }; for (const { mesh, part, from } of moving) { placePart(mesh, part, from); mesh.updateMatrixWorld(true); } - id = frame(step); - return () => cancel(id); + return step; } /**