Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions agent-notes/perf-occupant-lighting.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Goal

Keep the room's static scene and lighting bake across occupant-only changes, and suppress identical full snapshots.

## State

Implementation in the independent react-client-occupant-lighting worktree based on master. The room store compares decoded snapshots. The room view retains unchanged occupant meshes and labels, removes departed people and adds arrivals with the current environment.

## Decisions and why

The capture excludes people but includes real light sources. Check room identity, dimensions, finishes, exits, room light, placed sources, and static things before reusing that capture. Start from master so this work does not depend on the open first-paint PR.

## Surprises

Figure geometry belongs to a shared cache. Retain geometry still in use when a different figure leaves, and give each person's disposable materials an independent lifetime.

## Next step

The focused room scene and component tests passed. In a headless Edge replay an identical snapshot, departure and arrival during baking kept one lighting capture and the same wall and unchanged person's mesh. After the bake finished, a second departure and arrival retained its environment. Adding, moving, then removing a lamp took the capture count from one to four. Publish the PR, follow CI, and merge the checked head.
63 changes: 61 additions & 2 deletions src/components/RoomLayout3D.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { fireEvent, render } from "@testing-library/react";
import { afterEach, expect, it, vi } from "vitest";
import { sampleLayout } from "../map/roomLayout.fixture";
import { crowdLayout, sampleLayout } from "../map/roomLayout.fixture";
import { placeThings } from "../map/roomLayout";
import { type BufferGeometry, type Mesh, type MeshStandardMaterial, Texture } from "three";
import { useRoomStore } from "../stores/roomStore";
import { lightRoom } from "../map/roomBounce";
import * as roomScene from "../map/roomScene";
import RoomLayout3D from "./RoomLayout3D";

Expand All @@ -16,14 +20,69 @@ vi.mock("../map/roomPost", () => ({
roomPost: () => ({ setRoom: vi.fn(), setSize: vi.fn(), render: draw, dispose: vi.fn() }),
}));
vi.mock("../map/roomBounce", () => ({
lightRoom: () => ({ baked: new Promise<void>((resolve) => { finishBake = resolve; }), dispose: vi.fn() }),
lightRoom: vi.fn(() => ({ environment: new Texture(), baked: new Promise<void>((resolve) => { finishBake = resolve; }), dispose: vi.fn() })),
}));

afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllGlobals();
});

it("keeps the room, environment and unchanged people through occupant snapshots; emitting lights invalidate the bake", () => {
vi.stubGlobal("requestAnimationFrame", () => 1);
vi.stubGlobal("cancelAnimationFrame", vi.fn());
vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue({} as WebGL2RenderingContext);
vi.mocked(lightRoom).mockClear();
const layout = crowdLayout(2);
const picture = (data: typeof layout, selectedId: string | null) => <RoomLayout3D layout={data} placed={placeThings(data)}
youId="" label="Room" mode="dollhouse" selectedId={selectedId} onSelect={vi.fn()} onExit={vi.fn()} onFitting={vi.fn()} onInspect={vi.fn()} />;
const view = render(picture(layout, "#p1"));
const room = vi.mocked(lightRoom).mock.calls[0][2];
const light = vi.mocked(lightRoom).mock.results[0].value;
const original = room.things.get("#p0");
const marker = room.markers.get("#p0");
const label = view.container.querySelector(".rl3d-label-person");
const fewer = structuredClone(layout);
fewer.things.pop();
view.rerender(picture(fewer, "#p1"));
expect(room.things.has("#p1")).toBe(false);
expect(room.heads.has("#p1")).toBe(false);
expect(room.markers.has("#p1")).toBe(false);
expect(room.things.get("#p0")).toBe(original);
expect(room.markers.get("#p0")).toBe(marker);
expect(label?.isConnected).toBe(true);
view.rerender(picture(structuredClone(layout), "#p1"));
expect(view.container.querySelector(".rl3d-label-selected")?.textContent).toBeTruthy();
const added = room.things.get("#p1")!.children[0] as Mesh<BufferGeometry, MeshStandardMaterial>;
expect(added.material.envMap).toBe(light.environment);
expect(lightRoom).toHaveBeenCalledTimes(1);
expect(light.dispose).not.toHaveBeenCalled();
const lit = structuredClone(layout);
lit.things[1].light = { on: true, lumens: 500, cct: 2700, shape: "point" };
view.rerender(picture(lit, "#p1"));
expect(lightRoom).toHaveBeenCalledTimes(2);
expect(light.dispose).toHaveBeenCalledOnce();
view.rerender(picture(fewer, null));
expect(lightRoom).toHaveBeenCalledTimes(3);
view.unmount();
});

it("retains the stored layout for an identical decoded snapshot", () => {
const layout = crowdLayout(2);
useRoomStore.getState().reset();
useRoomStore.getState().setRoomLayout(layout);
const updated = vi.fn();
const unsubscribe = useRoomStore.subscribe(updated);
try {
useRoomStore.getState().setRoomLayout(structuredClone(layout));
expect(updated).not.toHaveBeenCalled();
expect(useRoomStore.getState().roomLayout).toBe(layout);
} finally {
unsubscribe();
useRoomStore.getState().reset();
}
});

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);
Expand Down
66 changes: 48 additions & 18 deletions src/components/RoomLayout3D.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
jointPositions,
jointSwingMs,
updateRoomBodies,
updateRoomOccupants,
type CameraMode,
type CameraPose,
cutWalls,
Expand Down Expand Up @@ -57,7 +58,8 @@ import {
zoomedFovBy,
} from "../map/roomScene";
import { roomRenderer } from "../map/roomRenderer";
import { needsNightVision } from "../map/lightUnits";
import { needsNightVision, placedLights } from "../map/lightUnits";
import { sameRoomData } from "../stores/roomStore";
import { type RoomPost, roomPost } from "../map/roomPost";
import { lightRoom, type RoomLight } from "../map/roomBounce";
import { useSpatialStore } from "../stores/spatialStore";
Expand Down Expand Up @@ -122,6 +124,7 @@ interface Stage {
lastDrawn: RoomScene | null;
layout: RoomLayout | null;
placed: PlacedThing[];
youId: string;
/** People's figure geometries, reused while their look is unchanged. */
figures: FigureCache;
/** The current room's light bounced off its own surfaces (`lightRoom`): probe grid and reflected environment. */
Expand Down Expand Up @@ -242,6 +245,7 @@ const RoomLayout3D: React.FC<RoomLayout3DProps> = ({ layout, placed, youId, labe
lastDrawn: null,
layout: null,
placed: [],
youId: "",
figures: new FigureCache(),
light: null,
post: roomPost(renderer, scene, camera),
Expand Down Expand Up @@ -354,13 +358,18 @@ const RoomLayout3D: React.FC<RoomLayout3DProps> = ({ layout, placed, youId, labe
}
}

// Rigid body updates retain the room's meshes and camera. Structural snapshots rebuild it.
// Body deltas retain the room dimensions by reference. Full snapshots arrive as freshly decoded records.
useEffect(() => {
const stage = stageRef.current;
if (!stage) return;
if (mode === "dollhouse") stage.controls.maxDistance = dollhouseMaxDistance(layout);
if (stage.room && stage.layout?.size === layout.size && stage.layout.exits === layout.exits &&
stage.layout.finishes === layout.finishes && stage.layout.light === layout.light && updateRoomBodies(stage.room, stage.placed, placed)) {
const old = stage.layout;
const sameShell = old && old.num === layout.num && old.room_lifetime === layout.room_lifetime &&
sameRoomData(old.size, layout.size) && sameRoomData(old.exits, layout.exits) &&
sameRoomData(old.finishes, layout.finishes) && sameRoomData(old.light, layout.light);
const sameLights = sameShell && (stage.placed === placed || sameRoomData(placedLights(stage.placed), placedLights(placed)));
if (stage.room && sameLights && old?.size === layout.size && stage.youId === youId &&
updateRoomBodies(stage.room, stage.placed, placed)) {
stage.layout = layout;
stage.placed = placed;
for (const [id, object] of stage.labelObjects) {
Expand All @@ -375,18 +384,42 @@ const RoomLayout3D: React.FC<RoomLayout3DProps> = ({ layout, placed, youId, labe
return;
}
const previous = stage.room;
if (previous) stage.scene.remove(previous.root);
for (const object of stage.labelObjects.values()) object.removeFromParent();
stage.labelObjects.clear();

// A door or drawer that moved swings or slides there from where it was drawn, unless motion is reduced.
const drawnJoints = previous ? jointPositions(previous) : new Map<string, number>();
const room = buildRoomScene({ layout, placed, youId, figures: stage.figures });
stage.room = room;
// The capture hides people but still sees their light sources, checked above.
const staticThings = (items: PlacedThing[]) => items.filter(p => !isPerson(p.thing)).map(p => p.thing);
const keepRoom = sameLights && sameRoomData(staticThings(stage.placed), staticThings(placed));
const kept = new Set<string>();
if (keepRoom) {
const before = new Map(stage.placed.map(p => [p.thing.id, p.thing]));
for (const { thing } of placed) {
if ((thing.id === stage.youId) === (thing.id === youId) && sameRoomData(before.get(thing.id), thing)) kept.add(thing.id);
}
}
if (stage.selection) disposeSelectionOutline(stage.selection);
stage.selection = null;
for (const [id, object] of stage.labelObjects) {
if (kept.has(id)) continue;
object.removeFromParent();
stage.labelObjects.delete(id);
}

let room: RoomScene;
if (previous && keepRoom) {
room = previous;
updateRoomOccupants(room, placed, youId, stage.figures, stage.light?.environment, kept);
} else {
if (previous) stage.scene.remove(previous.root);
const drawnJoints = previous ? jointPositions(previous) : new Map<string, number>();
room = buildRoomScene({ layout, placed, youId, figures: stage.figures });
stage.room = room;
stage.scene.add(room.root);
lightStage(stage, room, layout);
stage.stepJoints = animateJoints(room, drawnJoints,
jointSwingMs(typeof window.matchMedia === "function" ? (query) => window.matchMedia(query) : undefined));
if (previous && previous !== stage.lastDrawn) disposeRoomScene(previous);
}
stage.layout = layout;
stage.placed = placed;
stage.scene.add(room.root);
lightStage(stage, room, layout);
stage.youId = youId;
// In your own eyes you are not drawn.
const you = room.things.get(youId);
if (you) you.visible = mode !== "eyes";
Expand All @@ -403,6 +436,7 @@ const RoomLayout3D: React.FC<RoomLayout3DProps> = ({ layout, placed, youId, labe
];
labelPlan.current = plan;
for (const { id, text, person } of plan) {
if (stage.labelObjects.has(id)) continue;
const points = room.labelPoints.get(id);
const group = room.things.get(id);
if (!points || !group) continue;
Expand All @@ -424,12 +458,8 @@ const RoomLayout3D: React.FC<RoomLayout3DProps> = ({ layout, placed, youId, labe
stage.labelObjects.set(id, object);
}
showSelection(stage, selectedIdRef.current);
// Set before the first frame, so a moving part is first drawn where it was.
stage.stepJoints = animateJoints(room, drawnJoints,
jointSwingMs(typeof window.matchMedia === "function" ? (query) => window.matchMedia(query) : undefined));
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.
Expand Down
4 changes: 2 additions & 2 deletions src/map/figureMesh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1736,9 +1736,9 @@ export class FigureCache {
}

/** Frees every geometry not asked for since the last sweep: people who left or whose look changed. */
sweep(): void {
sweep(retained?: Set<THREE.BufferGeometry>): void {
for (const [key, geometry] of this.geometries) {
if (this.used.has(key)) continue;
if (this.used.has(key) || retained?.has(geometry)) continue;
geometry.dispose();
this.geometries.delete(key);
}
Expand Down
22 changes: 22 additions & 0 deletions src/map/roomScene.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
jointSwingMs,
JOINT_ANIMATION_MS,
updateRoomBodies,
updateRoomOccupants,
CUT_WALL_HEIGHT,
cutWalls,
DEFAULT_EYE_HEIGHT,
Expand Down Expand Up @@ -171,6 +172,27 @@ describe("picking and the selection in 3D", () => {
});

describe("buildRoomScene", () => {
it("keeps shared figure geometry and marker rings until their last occupant leaves", () => {
const layout = crowdLayout(2, [TEST_CHARACTERS[0]]);
const figures = new FigureCache();
const placed = placeThings(layout);
const room = buildRoomScene({ layout, placed, figures, youId: "" });
const first = room.things.get("#p0")!.children[0] as THREE.Mesh;
const second = room.things.get("#p1")!.children[0] as THREE.Mesh;
expect(first.geometry).toBe(second.geometry);
const freeFigure = vi.spyOn(first.geometry, "dispose");
const freeRing = vi.spyOn(room.markers.get("#p0")!.geometry, "dispose");
updateRoomOccupants(room, placed.slice(1), "", figures, undefined, new Set(["#p1"]));
expect(freeFigure).not.toHaveBeenCalled();
expect(freeRing).not.toHaveBeenCalled();
expect(room.things.get("#p1")!.children[0]).toBe(second);
updateRoomOccupants(room, [], "", figures);
expect(freeFigure).toHaveBeenCalledOnce();
expect(freeRing).toHaveBeenCalledOnce();
expect(figures.size).toBe(0);
disposeRoomScene(room);
});

it("paints individual form parts with the MOO palette and falls back to the host material", () => {
const layout = livingRoomLayout();
const fitting = { id: "#123", name: "drawer", lifetime: "1", command: "open #123", opened: false, contents: [] };
Expand Down
Loading