Skip to content
Source
Sign inSign up
samwillis/neonbricks
Open History to see the last commit

Scene.tsx

766 lines23.2 KB

1import { useEffect, useMemo, useRef } from "react";
2import {
3 Canvas,
4 type ThreeEvent,
5 useThree,
6 useFrame,
7} from "@react-three/fiber";
8import { OrbitControls, ContactShadows, Edges, Html } from "@react-three/drei";
9import * as THREE from "three";
10import type { OrbitControls as OrbitImpl } from "three-stdlib";
11import { CATALOGUE, BY_KEY } from "../shared/catalogue";
12import type { Part, Preview, Viewer } from "../shared/types";
13import { dimensions, bounds as boundsForHandles } from "../shared/geometry";
14import { model } from "./shapes";
15import type { Position } from "../shared/types";
16import { installGestures } from "./gestures";
17import type { DragSurface } from "./snapping";
18import { installCursorTracking } from "./cursors";
19import { CursorMotion } from "./cursor-motion";
20export type FrameMetrics = {
21 p95: number;
22 fps: number;
23 calls: number;
24 triangles: number;
25 samples: number;
26};
27type Props = {
28 theme: "light" | "dark";
29 parts: Part[];
30 selected: string[];
31 ghosts: Preview[];
32 valid: boolean;
33 viewers: Viewer[];
34 guest: string;
35 generation: number;
36 grid: boolean;
37 quality: boolean;
38 cameraMode: string;
39 frameParts?: boolean;
40 presentation: boolean;
41 selectMode: boolean;
42 canMove: boolean;
43 dragging: boolean;
44 onGrab: (part?: Part, shift?: boolean) => boolean;
45 onDrag: (delta: Position, hover?: DragSurface) => void;
46 onDrop: () => void;
47 onCancelDrag: () => void;
48 onMetrics?: (m: FrameMetrics) => void;
49 onCursor: (point: Position | null) => void;
50 onHover: (
51 point: THREE.Vector3,
52 normal: THREE.Vector3 | undefined,
53 part?: Part,
54 ) => void;
55 onClick: (p?: Part, shift?: boolean) => void;
56};
57const temp = new THREE.Object3D(),
58 color = new THREE.Color();
59function Instances({
60 partKey,
61 parts,
62 selected,
63 onHover,
64 onClick,
65}: {
66 partKey: string;
67 parts: Part[];
68 selected: string[];
69 onHover: Props["onHover"];
70 onClick: Props["onClick"];
71}) {
72 const def = BY_KEY[partKey],
73 g = useMemo(() => model(def), [def]);
74 const body = useRef<THREE.InstancedMesh>(null),
75 detail = useRef<THREE.InstancedMesh>(null);
76 const slots = useRef(new Map<string, number>()),
77 bySlot = useRef(new Map<number, Part>()),
78 signatures = useRef(new Map<string, string>());
79 useEffect(() => {
80 if (!body.current) return;
81 const live = new Set(parts.map((p) => p.id));
82 for (const [id, i] of slots.current)
83 if (!live.has(id)) {
84 temp.position.set(0, -100, 0);
85 temp.scale.setScalar(0);
86 temp.updateMatrix();
87 body.current.setMatrixAt(i, temp.matrix);
88 detail.current?.setMatrixAt(i, temp.matrix);
89 slots.current.delete(id);
90 bySlot.current.delete(i);
91 signatures.current.delete(id);
92 }
93 for (const p of parts) {
94 let i = slots.current.get(p.id);
95 if (i === undefined) {
96 i = 0;
97 while (bySlot.current.has(i)) i++;
98 if (i >= 4096) continue;
99 slots.current.set(p.id, i);
100 }
101 bySlot.current.set(i, p);
102 const signature = `${p.revision}/${p.position.x}/${p.position.y}/${p.position.z}/${p.rotation}/${p.color}/${selected.includes(p.id)}`;
103 if (signatures.current.get(p.id) === signature) continue;
104 signatures.current.set(p.id, signature);
105 const d = BY_KEY[p.key],
106 a = (p.rotation * Math.PI) / 2;
107 temp.scale.setScalar(1);
108 temp.rotation.set(0, -a, 0);
109 temp.position.set(
110 p.position.x / 6 +
111 (p.rotation === 1 ? d.d : p.rotation === 2 ? d.w : 0),
112 p.position.y / 6,
113 p.position.z / 6 +
114 (p.rotation === 2 ? d.d : p.rotation === 3 ? d.w : 0),
115 );
116 temp.updateMatrix();
117 body.current.setMatrixAt(i, temp.matrix);
118 detail.current?.setMatrixAt(i, temp.matrix);
119 color.set(def.shape === "wheel" ? "#343b3a" : p.color);
120 if (selected.includes(p.id)) color.lerp(new THREE.Color("#ffffff"), 0.25);
121 body.current.setColorAt(i, color);
122 detail.current?.setColorAt(
123 i,
124 new THREE.Color(
125 def.shape === "wheel" ? "#b4b9b0" : p.color,
126 ).multiplyScalar(0.85),
127 );
128 }
129 const count = Math.max(0, ...bySlot.current.keys()) + 1;
130 body.current.count = parts.length ? count : 0;
131 body.current.instanceMatrix.needsUpdate = true;
132 if (body.current.instanceColor)
133 body.current.instanceColor.needsUpdate = true;
134 body.current.computeBoundingSphere();
135 if (detail.current) {
136 detail.current.count = body.current.count;
137 detail.current.instanceMatrix.needsUpdate = true;
138 if (detail.current.instanceColor)
139 detail.current.instanceColor.needsUpdate = true;
140 detail.current.computeBoundingSphere();
141 }
142 }, [parts, selected, def]);
143 const hover = (e: ThreeEvent<PointerEvent>) => {
144 if (e.buttons) return;
145 e.stopPropagation();
146 const p = bySlot.current.get(e.instanceId ?? -1);
147 const n = e.face?.normal.clone();
148 if (n && p)
149 n.applyAxisAngle(new THREE.Vector3(0, 1, 0), (-p.rotation * Math.PI) / 2);
150 onHover(e.point, n, p);
151 };
152 const click = (e: ThreeEvent<MouseEvent>) => {
153 if (e.delta > 5) return;
154 e.stopPropagation();
155 onClick(bySlot.current.get(e.instanceId ?? -1), e.shiftKey);
156 };
157 const pickData = { partAt: (i: number) => bySlot.current.get(i) };
158 return (
159 <group>
160 <instancedMesh
161 ref={body}
162 args={[g.body, undefined, 4096]}
163 castShadow
164 receiveShadow
165 onPointerMove={hover}
166 onClick={click}
167 dispose={null}
168 userData={pickData}
169 >
170 <meshStandardMaterial roughness={0.31} metalness={0.02} />
171 </instancedMesh>
172 {g.detail && (
173 <instancedMesh
174 ref={detail}
175 args={[g.detail, undefined, 4096]}
176 castShadow
177 receiveShadow
178 onPointerMove={hover}
179 onClick={click}
180 dispose={null}
181 userData={pickData}
182 >
183 <meshStandardMaterial roughness={0.4} metalness={0.16} />
184 </instancedMesh>
185 )}
186 </group>
187 );
189function Piece({
190 part,
191 opacity = 1,
192 tint,
193}: {
194 part: Preview;
195 opacity?: number;
196 tint?: string;
197}) {
198 const d = BY_KEY[part.key];
199 if (!d) return null;
200 const g = model(d),
201 r = part.rotation;
202 return (
203 <group
204 position={[
205 part.position.x / 6 + (r === 1 ? d.d : r === 2 ? d.w : 0),
206 part.position.y / 6,
207 part.position.z / 6 + (r === 2 ? d.d : r === 3 ? d.w : 0),
208 ]}
209 rotation={[0, (-r * Math.PI) / 2, 0]}
210 >
211 <mesh geometry={g.body} dispose={null} raycast={() => {}}>
212 <meshStandardMaterial
213 color={tint || part.color}
214 transparent
215 opacity={opacity}
216 roughness={0.3}
217 depthWrite={opacity === 1}
218 />
219 </mesh>
220 {g.detail && (
221 <mesh geometry={g.detail} dispose={null} raycast={() => {}}>
222 <meshStandardMaterial
223 color={tint || part.color}
224 transparent
225 opacity={opacity}
226 roughness={0.5}
227 depthWrite={opacity === 1}
228 />
229 </mesh>
230 )}
231 </group>
232 );
234const noParts: Part[] = [];
235function Camera({ mode, parts = noParts }: { mode: string; parts?: Part[] }) {
236 const { camera, size } = useThree(),
237 controls = useRef<OrbitImpl>(null);
238 const framed = useRef("");
239 useEffect(() => {
240 if (parts.length && mode.startsWith("iso")) {
241 if (framed.current === mode) return;
242 const box = new THREE.Box3();
243 for (const part of parts) {
244 const b = boundsForHandles(part);
245 box.expandByPoint(
246 new THREE.Vector3(b.minx / 6, b.miny / 6, b.minz / 6),
247 );
248 box.expandByPoint(
249 new THREE.Vector3(b.maxx / 6, b.maxy / 6, b.maxz / 6),
250 );
251 }
252 const center = box.getCenter(new THREE.Vector3());
253 const radius = box.getSize(new THREE.Vector3()).length() / 2;
254 const angle = Math.atan(
255 Math.tan(
256 THREE.MathUtils.degToRad((camera as THREE.PerspectiveCamera).fov / 2),
257 ) * Math.min(1, size.width / size.height),
258 );
259 const distance = Math.min(
260 60,
261 Math.max(7, (radius / Math.sin(angle)) * 1.25),
262 );
263 camera.position
264 .copy(center)
265 .add(
266 new THREE.Vector3(22, 22, 27).normalize().multiplyScalar(distance),
267 );
268 controls.current?.target.copy(center);
269 controls.current?.update();
270 framed.current = mode;
271 return;
272 }
273 const poses: Record<string, number[]> = {
274 iso: [22, 22, 27],
275 top: [0, 34, 0.001],
276 front: [0, 11, 32],
277 side: [32, 11, 0],
278 };
279 const p = poses[mode.split(":")[0]] || poses.iso;
280 camera.position.set(p[0], p[1], p[2]);
281 controls.current?.target.set(0, 1, 0);
282 controls.current?.update();
283 }, [mode, camera, parts, size.width, size.height]);
284 return (
285 <OrbitControls
286 ref={controls}
287 makeDefault
288 enableDamping
289 dampingFactor={0.12}
290 minDistance={5}
291 maxDistance={65}
292 maxPolarAngle={Math.PI / 2 - 0.015}
293 target={[0, 1, 0]}
294 mouseButtons={{
295 LEFT: THREE.MOUSE.ROTATE,
296 MIDDLE: THREE.MOUSE.DOLLY,
297 RIGHT: THREE.MOUSE.PAN,
298 }}
299 />
300 );
302​
303// Capture runs before OrbitControls' native pointer listener, so a brick never
304// starts a camera gesture. Native pointer capture also covers release off-board.
305function Gestures(p: Props) {
306 const { gl, camera, scene, controls } = useThree();
307 const latest = useRef(p);
308 const abort = useRef<() => void>(() => {});
309 const cursor = useRef<ReturnType<typeof installCursorTracking> | null>(null);
310 const lastCursorFrame = useRef(0);
311 latest.current = p;
312 useFrame(({ clock }) => {
313 if (
314 latest.current.presentation ||
315 clock.elapsedTime - lastCursorFrame.current < 0.1
316 )
317 return;
318 lastCursorFrame.current = clock.elapsedTime;
319 cursor.current?.update();
320 });
321 useEffect(() => {
322 // Register first, before a brick drag stops native pointer propagation.
323 const tracking = installCursorTracking(
324 gl.domElement,
325 camera,
326 scene,
327 (point) =>
328 latest.current.onCursor(latest.current.presentation ? null : point),
329 );
330 cursor.current = tracking;
331 const gestures = installGestures(
332 gl.domElement,
333 camera,
334 scene,
335 controls as OrbitImpl | null,
336 () => latest.current,
337 );
338 abort.current = gestures.cancel;
339 return () => {
340 tracking.dispose();
341 cursor.current = null;
342 gestures.dispose();
343 };
344 }, [gl, camera, scene, controls]);
345 useEffect(() => {
346 if (!p.canMove || p.presentation || !p.selectMode) abort.current();
347 }, [p.canMove, p.presentation, p.selectMode]);
348 useEffect(() => {
349 abort.current();
350 }, [p.generation, p.cameraMode]);
351 useEffect(() => {
352 cursor.current?.clear();
353 }, [p.generation, p.presentation]);
354 useEffect(() => {
355 cursor.current?.invalidate();
356 }, [p.parts]);
357 return null;
359​
360function CollaboratorCursor({
361 viewer,
362}: {
363 viewer: Viewer & { cursor: Position };
364}) {
365 const root = useRef<THREE.Group>(null);
366 const target = useMemo(
367 () =>
368 new THREE.Vector3(
369 viewer.cursor.x / 6,
370 viewer.cursor.y / 6,
371 viewer.cursor.z / 6,
372 ),
373 [viewer.cursor.x, viewer.cursor.y, viewer.cursor.z],
374 );
375 const initial = useRef(target.clone());
376 const motion = useRef<CursorMotion | null>(null);
377 if (!motion.current) motion.current = new CursorMotion(target);
378 useEffect(() => {
379 motion.current!.receive(target, performance.now());
380 }, [target, viewer.cursor_at]);
381 useFrame((_, delta) => {
382 motion.current!.advance(delta);
383 root.current?.position.copy(motion.current!.position);
384 });
385 return (
386 <group ref={root} position={initial.current}>
387 <Html zIndexRange={[6, 0]} style={{ pointerEvents: "none" }}>
388 <div
389 className="collaborator-cursor"
390 data-viewer={viewer.id}
391 aria-label={`${viewer.name}'s cursor`}
392 style={{ color: viewer.color }}
393 >
394 <svg width="22" height="26" viewBox="0 0 22 26" aria-hidden="true">
395 <path
396 d="M1 1L19 16L11 17L7 24Z"
397 fill="currentColor"
398 stroke="white"
399 strokeWidth="1.5"
400 strokeLinejoin="round"
401 />
402 </svg>
403 <span className="remote-label" style={{ borderColor: viewer.color }}>
404 <i style={{ background: viewer.color }} />
405 {viewer.name}
406 </span>
407 </div>
408 </Html>
409 </group>
410 );
412​
413function MoveHandles({ parts }: { parts: Part[] }) {
414 const root = useRef<THREE.Group>(null);
415 const labels = useRef<Array<HTMLSpanElement | null>>([]);
416 const { camera, size } = useThree();
417 const center = useMemo(() => {
418 const bs = parts.map(boundsForHandles);
419 return new THREE.Vector3(
420 (Math.min(...bs.map((b) => b.minx)) +
421 Math.max(...bs.map((b) => b.maxx))) /
422 12,
423 Math.max(...bs.map((b) => b.maxy)) / 6 + 0.12,
424 (Math.min(...bs.map((b) => b.minz)) +
425 Math.max(...bs.map((b) => b.maxz))) /
426 12,
427 );
428 }, [parts]);
429 useFrame(() => {
430 if (!root.current) return;
431 root.current.scale.setScalar(
432 (camera.position.distanceTo(center) *
433 Math.tan(
434 THREE.MathUtils.degToRad((camera as THREE.PerspectiveCamera).fov / 2),
435 ) *
436 120) /
437 size.height,
438 );
439 const direction = camera.getWorldDirection(new THREE.Vector3());
440 root.current.children.forEach((child, i) => {
441 child.visible = Math.abs(direction[(["x", "y", "z"] as const)[i]]) < 0.98;
442 const label = labels.current[i];
443 if (label) label.style.display = child.visible ? "" : "none";
444 });
445 });
446 return (
447 <group ref={root} position={center}>
448 {(["x", "y", "z"] as const).map((axis, i) => (
449 <group
450 key={axis}
451 rotation={
452 axis === "x"
453 ? [0, 0, -Math.PI / 2]
454 : axis === "z"
455 ? [Math.PI / 2, 0, 0]
456 : [0, 0, 0]
457 }
458 >
459 <mesh position={[0, 0.65, 0]} renderOrder={10} raycast={() => {}}>
460 <cylinderGeometry args={[0.025, 0.025, 1.3, 12]} />
461 <meshBasicMaterial
462 color={["#cb715b", "#289b74", "#588db5"][i]}
463 depthTest={false}
464 />
465 </mesh>
466 <mesh position={[0, 1.4, 0]} renderOrder={10} raycast={() => {}}>
467 <coneGeometry args={[0.09, 0.28, 16]} />
468 <meshBasicMaterial
469 color={["#cb715b", "#289b74", "#588db5"][i]}
470 depthTest={false}
471 />
472 </mesh>
473 <mesh position={[0, 0.85, 0]} userData={{ moveAxis: axis }}>
474 <cylinderGeometry args={[0.15, 0.15, 1.4, 8]} />
475 <meshBasicMaterial transparent opacity={0} depthWrite={false} />
476 </mesh>
477 <Html
478 position={[0, 1.75, 0]}
479 zIndexRange={[5, 0]}
480 center
481 style={{ pointerEvents: "none" }}
482 >
483 <span
484 ref={(el) => {
485 labels.current[i] = el;
486 }}
487 className={`move-axis axis-${axis}`}
488 >
489 {axis.toUpperCase()}
490 </span>
491 </Html>
492 </group>
493 ))}
494 </group>
495 );
497function Contents(p: Props) {
498 const dark = p.theme === "dark";
499 const palette = dark
500 ? {
501 background: "#101214",
502 floor: "#14181c",
503 edge: "#242a30",
504 board: "#30383d",
505 grid: "#525f65",
506 minorGrid: "#414c52",
507 accent: "#34d59a",
508 }
509 : {
510 background: "#edf0f2",
511 floor: "#e8ecef",
512 edge: "#b9c4ca",
513 board: "#d8e1e4",
514 grid: "#a0b2ba",
515 minorGrid: "#bccbd0",
516 accent: "#087b56",
517 };
518 const selected = p.parts.filter((part) => p.selected.includes(part.id));
519 const groups = useMemo(
520 () =>
521 Object.fromEntries(
522 CATALOGUE.map((d) => [d.key, p.parts.filter((p) => p.key === d.key)]),
523 ),
524 [p.parts],
525 );
526 return (
527 <>
528 {p.onMetrics && <FrameStats onMetrics={p.onMetrics} />}
529 <color attach="background" args={[palette.background]} />
530 <fog attach="fog" args={[palette.background, 65, 120]} />
531 <ambientLight intensity={dark ? 1.1 : 1.4} color="#ffffff" />
532 <hemisphereLight args={["#eff5ff", dark ? "#748494" : "#c6cfd4", 2]} />
533 <directionalLight
534 position={[-12, 24, 10]}
535 intensity={3.7}
536 color="#ffffff"
537 castShadow
538 shadow-mapSize={p.quality ? [1024, 1024] : [2048, 2048]}
539 shadow-camera-left={-22}
540 shadow-camera-right={22}
541 shadow-camera-top={22}
542 shadow-camera-bottom={-22}
543 shadow-normalBias={0.035}
544 shadow-bias={-0.0001}
545 />
546 <directionalLight
547 position={[10, 12, -8]}
548 intensity={1.2}
549 color="#dbe7ee"
550 />
551 <mesh
552 rotation={[-Math.PI / 2, 0, 0]}
553 position={[0, -0.39, 0]}
554 receiveShadow
555 >
556 <planeGeometry args={[160, 160]} />
557 <meshStandardMaterial color={palette.floor} roughness={0.92} />
558 </mesh>
559 <mesh position={[0, -0.23, 0]} receiveShadow>
560 <boxGeometry args={[32.2, 0.34, 32.2]} />
561 <meshStandardMaterial color={palette.edge} roughness={0.75} />
562 </mesh>
563 <mesh
564 rotation={[-Math.PI / 2, 0, 0]}
565 position={[0, -0.048, 0]}
566 receiveShadow
567 userData={{ cursorSurface: true }}
568 onPointerMove={(e) => {
569 if (!e.buttons) {
570 e.stopPropagation();
571 p.onHover(e.point, new THREE.Vector3(0, 1, 0));
572 }
573 }}
574 onClick={(e) => {
575 if (e.delta <= 5) {
576 e.stopPropagation();
577 p.onClick(undefined, e.shiftKey);
578 }
579 }}
580 >
581 <planeGeometry args={[32, 32]} />
582 <meshStandardMaterial color={palette.board} roughness={0.84} />
583 </mesh>
584 {p.grid && !p.presentation && (
585 <gridHelper
586 args={[32, 32, palette.grid, palette.minorGrid]}
587 position={[0, -0.043, 0]}
588 />
589 )}
590 <Camera mode={p.cameraMode} parts={p.frameParts ? p.parts : noParts} />
591 <Gestures {...p} />
592 {CATALOGUE.map((d) => (
593 <Instances
594 key={d.key}
595 partKey={d.key}
596 parts={groups[d.key]}
597 selected={p.selected}
598 onHover={p.onHover}
599 onClick={p.onClick}
600 />
601 ))}
602 {!p.presentation &&
603 selected.map((part) => {
604 const d = dimensions(part);
605 return (
606 <mesh
607 key={part.id}
608 raycast={() => {}}
609 position={[
610 (part.position.x + d.x / 2) / 6,
611 (part.position.y + d.y / 2) / 6,
612 (part.position.z + d.z / 2) / 6,
613 ]}
614 >
615 <boxGeometry
616 args={[d.x / 6 + 0.035, d.y / 6 + 0.035, d.z / 6 + 0.035]}
617 />
618 <meshBasicMaterial transparent opacity={0} depthWrite={false} />
619 <Edges color={palette.accent} lineWidth={1.5} threshold={15} />
620 </mesh>
621 );
622 })}
623 {!p.presentation && p.selectMode && p.canMove && selected.length > 0 && (
624 <MoveHandles
625 parts={
626 p.dragging
627 ? p.ghosts.map((g, i) => ({
628 ...g,
629 id: `handle-${i}`,
630 revision: 0,
631 }))
632 : selected
633 }
634 />
635 )}
636 {!p.presentation &&
637 p.ghosts.map((part, i) => (
638 <Piece
639 key={i}
640 part={part}
641 opacity={0.62}
642 tint={p.valid ? "#34d59a" : "#f77569"}
643 />
644 ))}
645 {!p.presentation &&
646 p.viewers
647 .filter((v) => v.id !== p.guest && v.generation === p.generation)
648 .map((v) => (
649 <group key={v.id}>
650 {v.cursor && (
651 <CollaboratorCursor viewer={{ ...v, cursor: v.cursor }} />
652 )}
653 {v.preview && (
654 <Piece part={v.preview} opacity={0.3} tint={v.color} />
655 )}
656 {p.parts
657 .filter((part) => v.selection.includes(part.id))
658 .map((part) => {
659 const d = dimensions(part);
660 return (
661 <mesh
662 key={part.id}
663 raycast={() => {}}
664 position={[
665 (part.position.x + d.x / 2) / 6,
666 (part.position.y + d.y / 2) / 6,
667 (part.position.z + d.z / 2) / 6,
668 ]}
669 >
670 <boxGeometry
671 args={[d.x / 6 + 0.08, d.y / 6 + 0.08, d.z / 6 + 0.08]}
672 />
673 <meshBasicMaterial
674 transparent
675 opacity={0}
676 depthWrite={false}
677 />
678 <Edges color={v.color} lineWidth={2} threshold={15} />
679 </mesh>
680 );
681 })}
682 <Html
683 zIndexRange={[5, 0]}
684 position={
685 v.preview
686 ? [
687 v.preview.position.x / 6,
688 v.preview.position.y / 6 + 1.8,
689 v.preview.position.z / 6,
690 ]
691 : [0, 0, 0]
692 }
693 center
694 style={{
695 pointerEvents: "none",
696 display: v.preview && !v.cursor ? "block" : "none",
697 }}
698 >
699 <div className="remote-label">
700 <i style={{ background: v.color }} />
701 {v.name}
702 </div>
703 </Html>
704 </group>
705 ))}
706 {!p.quality && (
707 <ContactShadows
708 key={`${p.theme}:${p.parts.map((p) => `${p.id}:${p.revision}`).join(",")}`}
709 position={[0, -0.039, 0]}
710 opacity={dark ? 0.4 : 0.28}
711 scale={34}
712 blur={2.3}
713 far={8}
714 resolution={512}
715 frames={1}
716 />
717 )}
718 </>
719 );
721function FrameStats({ onMetrics }: { onMetrics: (m: FrameMetrics) => void }) {
722 const { gl } = useThree(),
723 samples = useRef<number[]>([]),
724 started = useRef(performance.now()),
725 last = useRef(0);
726 useFrame((_, delta) => {
727 const now = performance.now();
728 if (document.visibilityState !== "visible") {
729 started.current = now;
730 samples.current = [];
731 return;
732 }
733 if (now - started.current < 2000) return;
734 samples.current.push(delta * 1000);
735 if (samples.current.length > 600) samples.current.shift();
736 if (now - last.current < 1000) return;
737 last.current = now;
738 const sorted = [...samples.current].sort((a, b) => a - b),
739 mean =
740 samples.current.reduce((a, b) => a + b, 0) / samples.current.length;
741 onMetrics({
742 p95: sorted[Math.floor(sorted.length * 0.95)] || 0,
743 fps: 1000 / mean,
744 calls: gl.info.render.calls,
745 triangles: gl.info.render.triangles,
746 samples: sorted.length,
747 });
748 });
749 return null;
751export default function Scene(p: Props) {
752 return (
753 <Canvas
754 shadows
755 dpr={p.quality ? 1 : [1, 1.75]}
756 camera={{ position: [22, 22, 27], fov: 40, near: 0.1, far: 180 }}
757 gl={{
758 antialias: true,
759 toneMapping: THREE.ACESFilmicToneMapping,
760 toneMappingExposure: 1.1,
761 }}
762 >
763 <Contents {...p} />
764 </Canvas>
765 );