From 20efea84cb8fe1ea3f2132db299040d72e253110 Mon Sep 17 00:00:00 2001 From: JCNoguera <88061365+VmMad@users.noreply.github.com> Date: Thu, 22 Feb 2024 10:12:15 +0100 Subject: [PATCH] fix: relocate camera on window resize (#1160) Co-authored-by: Mario --- .../visualizer-threejs/CameraControls.tsx | 58 +++++++++++++------ 1 file changed, 40 insertions(+), 18 deletions(-) diff --git a/client/src/features/visualizer-threejs/CameraControls.tsx b/client/src/features/visualizer-threejs/CameraControls.tsx index 2419d39dc..18c36e95e 100644 --- a/client/src/features/visualizer-threejs/CameraControls.tsx +++ b/client/src/features/visualizer-threejs/CameraControls.tsx @@ -3,34 +3,56 @@ import { getCameraAngles } from "./utils"; import React, { useEffect } from "react"; import { useThree } from "@react-three/fiber"; import { CanvasElement } from "./enums"; -import { useTangleStore } from "./store"; import { VISUALIZER_PADDINGS } from "./constants"; +const CAMERA_ANGLES = getCameraAngles(); + const CameraControls = () => { - const [shouldLockZoom, setShouldLockZoom] = React.useState(false); const controls = React.useRef(null); - const CAMERA_ANGLES = getCameraAngles(); + const scene = useThree((state) => state.scene); + const mesh = scene.getObjectByName(CanvasElement.TangleWrapperMesh) as THREE.Mesh | undefined; - const zoom = useTangleStore((s) => s.zoom); - const get = useThree((state) => state.get); - const mesh = get().scene.getObjectByName(CanvasElement.TangleWrapperMesh); + /** + * Locks the camera zoom to the current zoom value. + */ + function lockCameraZoom(controls: DreiCameraControls) { + const zoom = controls.camera.zoom; + controls.maxZoom = zoom; + controls.minZoom = zoom; + } - // Set fixed zoom - useEffect(() => { - if (controls.current && shouldLockZoom) { - controls.current.maxZoom = zoom; - controls.current.minZoom = zoom; + /** + * Unlocks the camera zoom for free movement. + */ + function unlockCameraZoom(controls: DreiCameraControls) { + controls.maxZoom = Infinity; + controls.minZoom = 0.01; + } + + /** + * Fits the camera to the TangleMesh. + */ + function fitCameraToTangle(controls: DreiCameraControls | null, mesh?: THREE.Mesh) { + if (controls && mesh) { + unlockCameraZoom(controls); + controls.fitToBox(mesh, false, { ...VISUALIZER_PADDINGS }); + controls.setOrbitPoint(0, 0, 0); + lockCameraZoom(controls); } - }, [controls, zoom, shouldLockZoom]); + } - // Fix to TangleMesh + /** + * Fit camera to TangleMesh on mount and on window resize. + */ useEffect(() => { - if (controls.current && mesh) { - controls.current.fitToBox(mesh, false, { ...VISUALIZER_PADDINGS }); - controls.current.setOrbitPoint(0, 0, 0); - setShouldLockZoom(true); - } + const adjustCamera = () => fitCameraToTangle(controls.current, mesh); + adjustCamera(); + + window.addEventListener("resize", adjustCamera); + return () => { + window.removeEventListener("resize", adjustCamera); + }; }, [controls, mesh]); return ;