Refactor distance finding controls and move controls for improved functionality and performance

- Updated `getRoomsFromLines.ts` to filter valid line features before polygonization.
- Enhanced `distanceFindingControls.tsx` to streamline measurement line updates and improve text label rendering.
- Refactored `moveControls.tsx` to optimize event handling and asset movement logic, ensuring smoother interactions.
- Adjusted `selectionControls.tsx` to safely parse stored floor items from local storage.
- Commented out unused imports in `roboticArmInstances.tsx` for cleaner code.
- Modified `polygonGenerator.tsx` to ensure only valid line features are processed for polygon generation.
This commit is contained in:
2025-05-10 18:12:04 +05:30
parent 32b3247765
commit 87d1c4ae12
6 changed files with 622 additions and 526 deletions

View File

@@ -27,7 +27,12 @@ async function getRoomsFromLines(lines: Types.RefLines) {
}))
);
const lineFeatures = result.map(line => turf.lineString(line.map(p => p.position)));
const polygons = turf.polygonize(turf.featureCollection(lineFeatures));
const validLineFeatures = lineFeatures.filter((line) => {
const coords = line.geometry.coordinates;
return coords.length >= 4;
});
const polygons = turf.polygonize(turf.featureCollection(validLineFeatures));
let union: any[] = [];

View File

@@ -1,18 +1,27 @@
import React, { useEffect, useRef } from "react";
import { Vector3, Raycaster, BufferGeometry, LineBasicMaterial, Line, Object3D, Mesh } from "three";
import React, { useRef } from "react";
import {
Vector3,
Raycaster,
BufferGeometry,
LineBasicMaterial,
Line,
Mesh,
Group,
} from "three";
import { useThree, useFrame } from "@react-three/fiber";
import { Group } from "three";
import { Html } from "@react-three/drei";
import * as THREE from "three";
interface DistanceFindingControlsProps {
boundingBoxRef: React.RefObject<Mesh>;
object: number;
}
const DistanceFindingControls = ({ boundingBoxRef }: DistanceFindingControlsProps) => {
const DistanceFindingControls = ({
boundingBoxRef,
object,
}: DistanceFindingControlsProps) => {
const { camera, scene } = useThree();
// Refs for measurement lines
const line1 = useRef<Line>(null);
const line2 = useRef<Line>(null);
@@ -33,10 +42,9 @@ const DistanceFindingControls = ({ boundingBoxRef }: DistanceFindingControlsProp
negX: new BufferGeometry(),
posZ: new BufferGeometry(),
negZ: new BufferGeometry(),
posY: new BufferGeometry()
posY: new BufferGeometry(),
});
useFrame(() => {
if (!boundingBoxRef?.current) return;
@@ -48,7 +56,7 @@ const DistanceFindingControls = ({ boundingBoxRef }: DistanceFindingControlsProp
const size = {
x: bbox.max.x - bbox.min.x,
y: bbox.max.y - bbox.min.y,
z: bbox.max.z - bbox.min.z
z: bbox.max.z - bbox.min.z,
};
const vec = boundingBoxRef.current?.getWorldPosition(new Vector3()).clone();
@@ -58,46 +66,46 @@ const DistanceFindingControls = ({ boundingBoxRef }: DistanceFindingControlsProp
line: line1.current,
geometry: lineGeometries.current.posX,
direction: new Vector3(1, 0, 0), // Positive X
angle: 'pos',
angle: "pos",
mesh: textPosX,
vec,
size
size,
});
updateLine({
line: line2.current,
geometry: lineGeometries.current.negX,
direction: new Vector3(-1, 0, 0), // Negative X
angle: 'neg',
angle: "neg",
mesh: textNegX,
vec,
size
size,
});
updateLine({
line: line3.current,
geometry: lineGeometries.current.posZ,
direction: new Vector3(0, 0, 1), // Positive Z
angle: 'pos',
angle: "pos",
mesh: textPosZ,
vec,
size
size,
});
updateLine({
line: line4.current,
geometry: lineGeometries.current.negZ,
direction: new Vector3(0, 0, -1), // Negative Z
angle: 'neg',
angle: "neg",
mesh: textNegZ,
vec,
size
size,
});
updateLine({
line: line5.current,
geometry: lineGeometries.current.posY,
direction: new Vector3(0, -1, 0), // Down (Y)
angle: 'posY',
angle: "posY",
mesh: textPosY,
vec,
size
size,
});
});
@@ -108,15 +116,15 @@ const DistanceFindingControls = ({ boundingBoxRef }: DistanceFindingControlsProp
angle,
mesh,
vec,
size
size,
}: {
line: Line | null,
geometry: BufferGeometry,
direction: Vector3,
angle: string,
mesh: React.RefObject<Group>,
vec: Vector3,
size: { x: number, y: number, z: number }
line: Line | null;
geometry: BufferGeometry;
direction: Vector3;
angle: string;
mesh: React.RefObject<Group>;
vec: Vector3;
size: { x: number; y: number; z: number };
}) => {
if (!line) return;
@@ -142,14 +150,19 @@ const DistanceFindingControls = ({ boundingBoxRef }: DistanceFindingControlsProp
ray.params.Line.threshold = 0.1;
// Find intersection points
const wallsGroup = scene.children.find(val => val?.name.includes("Walls"));
const intersects = wallsGroup ? ray.intersectObjects([wallsGroup], true) : [];
const wallsGroup = scene.children.find((val) =>
val?.name.includes("Walls")
);
const intersects = wallsGroup
? ray.intersectObjects([wallsGroup], true)
: [];
// Find intersection point
if (intersects[0]) {
for (const intersect of intersects) {
if (intersect.object.name.includes("Wall")) {
points[1] = angle !== "posY" ? intersect.point : new Vector3(vec.x, 0, vec.z); // Floor
points[1] =
angle !== "posY" ? intersect.point : new Vector3(vec.x, 0, vec.z); // Floor
break;
}
}
@@ -178,72 +191,76 @@ const DistanceFindingControls = ({ boundingBoxRef }: DistanceFindingControlsProp
geometry.dispose();
geometry.setFromPoints([new Vector3(), new Vector3()]);
line.geometry = geometry;
const label = document.getElementById(mesh?.current?.name || "");
const label = document.getElementById(mesh?.current?.name ?? "");
if (label) label.innerText = "";
}
};
const Material = new LineBasicMaterial({ color: "red" });
const Material = new LineBasicMaterial({ color: "#d2baff" });
return (
<>
{/* Measurement text labels */}
{boundingBoxRef.current && (
{boundingBoxRef.current && object > 0 && (
<>
<group name="textPosX" ref={textPosX}>
<Html zIndexRange={[1, 0]} style={{ pointerEvents: 'none' }}>
<div className="distance-label" id="textPosX" style={{
background: 'rgba(0,0,0,0.7)',
color: 'white',
padding: '2px 5px',
borderRadius: '3px',
fontSize: '12px',
whiteSpace: 'nowrap'
}}></div>
<Html
wrapperClass="distance-text-wrapper"
className="distance-text"
zIndexRange={[1, 0]}
style={{ pointerEvents: "none" }}
>
<div className="distance-label" id="textPosX"></div>
</Html>
</group>
<group name="textNegX" ref={textNegX}>
<Html zIndexRange={[1, 0]} style={{ pointerEvents: 'none' }}>
<div className="distance-label" id="textNegX" style={{
background: 'rgba(0,0,0,0.7)',
color: 'white',
padding: '2px 5px',
borderRadius: '3px',
fontSize: '12px',
whiteSpace: 'nowrap'
}}></div>
<Html
wrapperClass="distance-text-wrapper"
className="distance-text"
zIndexRange={[1, 0]}
style={{ pointerEvents: "none" }}
>
<div className="distance-label" id="textNegX"></div>
</Html>
</group>
<group name="textPosZ" ref={textPosZ}>
<Html zIndexRange={[2, 0]} style={{ pointerEvents: 'none' }}>
<div className="distance-label" id="textPosZ" style={{
background: 'rgba(0,0,0,0.7)',
color: 'white',
padding: '2px 5px',
borderRadius: '3px',
fontSize: '12px',
whiteSpace: 'nowrap'
}}></div>
<Html
wrapperClass="distance-text-wrapper"
className="distance-text"
zIndexRange={[2, 0]}
style={{ pointerEvents: "none" }}
>
<div className="distance-label" id="textPosZ"></div>
</Html>
</group>
<group name="textNegZ" ref={textNegZ}>
<Html zIndexRange={[1, 0]} style={{ pointerEvents: 'none' }}>
<div className="distance-label" id="textNegZ" style={{
background: 'rgba(0,0,0,0.7)',
color: 'white',
padding: '2px 5px',
borderRadius: '3px',
fontSize: '12px',
whiteSpace: 'nowrap'
}}></div>
<Html
wrapperClass="distance-text-wrapper"
className="distance-text"
zIndexRange={[1, 0]}
style={{ pointerEvents: "none" }}
>
<div className="distance-label" id="textNegZ"></div>
</Html>
</group>
{/* Measurement lines */}
<primitive object={new Line(new BufferGeometry(), Material)} ref={line1} />
<primitive object={new Line(new BufferGeometry(), Material)} ref={line2} />
<primitive object={new Line(new BufferGeometry(), Material)} ref={line3} />
<primitive object={new Line(new BufferGeometry(), Material)} ref={line4} />
<primitive
object={new Line(new BufferGeometry(), Material)}
ref={line1}
/>
<primitive
object={new Line(new BufferGeometry(), Material)}
ref={line2}
/>
<primitive
object={new Line(new BufferGeometry(), Material)}
ref={line3}
/>
<primitive
object={new Line(new BufferGeometry(), Material)}
ref={line4}
/>
</>
)}
</>

View File

@@ -1,7 +1,12 @@
import * as THREE from "three";
import { useEffect, useMemo, useRef, useState } from "react";
import { useFrame, useThree } from "@react-three/fiber";
import { useFloorItems, useSelectedAssets, useSocketStore, useStartSimulation, useToggleView } from "../../../../store/store";
import {
useFloorItems,
useSelectedAssets,
useSocketStore,
useToggleView,
} from "../../../../store/store";
// import { setFloorItemApi } from '../../../../services/factoryBuilder/assest/floorAsset/setFloorItemApi';
import { toast } from "react-toastify";
import * as Types from "../../../../types/world/worldTypes";
@@ -13,10 +18,26 @@ import { upsertProductOrEventApi } from "../../../../services/simulation/UpsertP
import { snapControls } from "../../../../utils/handleSnap";
import DistanceFindingControls from "./distanceFindingControls";
function MoveControls({ movedObjects, setMovedObjects, itemsGroupRef, copiedObjects, setCopiedObjects, pastedObjects, setpastedObjects, duplicatedObjects, setDuplicatedObjects, selectionGroup, rotatedObjects, setRotatedObjects, boundingBoxRef }: any) {
function MoveControls({
movedObjects,
setMovedObjects,
itemsGroupRef,
copiedObjects,
setCopiedObjects,
pastedObjects,
setpastedObjects,
duplicatedObjects,
setDuplicatedObjects,
selectionGroup,
rotatedObjects,
setRotatedObjects,
boundingBoxRef,
}: any) {
const { camera, controls, gl, scene, pointer, raycaster } = useThree();
const plane = useMemo(() => new THREE.Plane(new THREE.Vector3(0, 1, 0), 0), []);
const plane = useMemo(
() => new THREE.Plane(new THREE.Vector3(0, 1, 0), 0),
[]
);
const { toggleView } = useToggleView();
const { selectedAssets, setSelectedAssets } = useSelectedAssets();
@@ -24,9 +45,11 @@ function MoveControls({ movedObjects, setMovedObjects, itemsGroupRef, copiedObje
const { floorItems, setFloorItems } = useFloorItems();
const { socket } = useSocketStore();
const itemsData = useRef<Types.FloorItems>([]);
const [keyEvent, setKeyEvent] = useState<"Ctrl" | "Shift" | "Ctrl+Shift" | "">("")
const email = localStorage.getItem('email')
const organization = (email!.split("@")[1]).split(".")[0];
const [keyEvent, setKeyEvent] = useState<
"Ctrl" | "Shift" | "Ctrl+Shift" | ""
>("");
const email = localStorage.getItem("email");
const organization = email!.split("@")[1].split(".")[0];
const updateBackend = (
productName: string,
@@ -38,9 +61,9 @@ function MoveControls({ movedObjects, setMovedObjects, itemsGroupRef, copiedObje
productName: productName,
productId: productId,
organization: organization,
eventDatas: eventData
})
}
eventDatas: eventData,
});
};
useEffect(() => {
if (!camera || !scene || toggleView || !itemsGroupRef.current) return;
@@ -59,8 +82,7 @@ function MoveControls({ movedObjects, setMovedObjects, itemsGroupRef, copiedObje
};
const onKeyUp = (event: KeyboardEvent) => {
// When any modifier is released, reset snap
const isModifierKey =
event.key === "Control" || event.key === "Shift";
const isModifierKey = event.key === "Control" || event.key === "Shift";
if (isModifierKey) {
setKeyEvent("");
@@ -87,25 +109,36 @@ function MoveControls({ movedObjects, setMovedObjects, itemsGroupRef, copiedObje
setMovedObjects([]);
itemsData.current = [];
}
setKeyEvent("")
setKeyEvent("");
};
const onKeyDown = (event: KeyboardEvent) => {
const keyCombination = detectModifierKeys(event);
if (pastedObjects.length > 0 || duplicatedObjects.length > 0 || rotatedObjects.length > 0) return;
if (
pastedObjects.length > 0 ||
duplicatedObjects.length > 0 ||
rotatedObjects.length > 0
)
return;
if (keyCombination === "Ctrl" || keyCombination === "Ctrl+Shift" || keyCombination === "Shift") {
if (
keyCombination === "Ctrl" ||
keyCombination === "Ctrl+Shift" ||
keyCombination === "Shift"
) {
// update state here
setKeyEvent(keyCombination)
setKeyEvent(keyCombination);
} else {
setKeyEvent("")
setKeyEvent("");
}
if (keyCombination === "G") {
if (selectedAssets.length > 0) {
moveAssets();
itemsData.current = floorItems.filter((item: { modelUuid: string }) => selectedAssets.some((asset: any) => asset.uuid === item.modelUuid));
itemsData.current = floorItems.filter((item: { modelUuid: string }) =>
selectedAssets.some((asset: any) => asset.uuid === item.modelUuid)
);
}
}
@@ -141,7 +174,20 @@ function MoveControls({ movedObjects, setMovedObjects, itemsGroupRef, copiedObje
canvasElement.removeEventListener("keydown", onKeyDown);
canvasElement?.removeEventListener("keyup", onKeyUp);
};
}, [camera, controls, scene, toggleView, selectedAssets, socket, floorItems, pastedObjects, duplicatedObjects, movedObjects, rotatedObjects, keyEvent]);
}, [
camera,
controls,
scene,
toggleView,
selectedAssets,
socket,
floorItems,
pastedObjects,
duplicatedObjects,
movedObjects,
rotatedObjects,
keyEvent,
]);
let moveSpeed = keyEvent === "Ctrl" || "Ctrl+Shift" ? 1 : 0.25;
@@ -181,7 +227,9 @@ function MoveControls({ movedObjects, setMovedObjects, itemsGroupRef, copiedObje
);
} else {
const box = new THREE.Box3();
movedObjects.forEach((obj: THREE.Object3D) => box.expandByObject(obj));
movedObjects.forEach((obj: THREE.Object3D) =>
box.expandByObject(obj)
);
const center = new THREE.Vector3();
box.getCenter(center);
@@ -196,16 +244,19 @@ function MoveControls({ movedObjects, setMovedObjects, itemsGroupRef, copiedObje
}
}
}
});
const moveAssets = () => {
const updatedItems = floorItems.filter((item: { modelUuid: string }) => !selectedAssets.some((asset: any) => asset.uuid === item.modelUuid));
const updatedItems = floorItems.filter(
(item: { modelUuid: string }) =>
!selectedAssets.some((asset: any) => asset.uuid === item.modelUuid)
);
setFloorItems(updatedItems);
setMovedObjects(selectedAssets);
selectedAssets.forEach((asset: any) => { selectionGroup.current.attach(asset); });
}
selectedAssets.forEach((asset: any) => {
selectionGroup.current.attach(asset);
});
};
const placeMovedAssets = () => {
if (movedObjects.length === 0) return;
@@ -223,26 +274,39 @@ function MoveControls({ movedObjects, setMovedObjects, itemsGroupRef, copiedObje
modelName: obj.userData.name,
modelfileID: obj.userData.modelId,
position: [worldPosition.x, worldPosition.y, worldPosition.z],
rotation: { x: obj.rotation.x, y: obj.rotation.y, z: obj.rotation.z, },
rotation: { x: obj.rotation.x, y: obj.rotation.y, z: obj.rotation.z },
isLocked: false,
isVisible: true
isVisible: true,
};
if (obj.userData.eventData) {
const eventData = useEventsStore.getState().getEventByModelUuid(obj.userData.modelUuid);
const productData = useProductStore.getState().getEventByModelUuid(useSelectedProduct.getState().selectedProduct.productId, obj.userData.modelUuid);
const eventData = useEventsStore
.getState()
.getEventByModelUuid(obj.userData.modelUuid);
const productData = useProductStore
.getState()
.getEventByModelUuid(
useSelectedProduct.getState().selectedProduct.productId,
obj.userData.modelUuid
);
if (eventData) {
useEventsStore.getState().updateEvent(obj.userData.modelUuid, {
position: [worldPosition.x, worldPosition.y, worldPosition.z],
rotation: [obj.rotation.x, obj.rotation.y, obj.rotation.z],
})
});
}
if (productData) {
const event = useProductStore.getState().updateEvent(useSelectedProduct.getState().selectedProduct.productId, obj.userData.modelUuid, {
const event = useProductStore
.getState()
.updateEvent(
useSelectedProduct.getState().selectedProduct.productId,
obj.userData.modelUuid,
{
position: [worldPosition.x, worldPosition.y, worldPosition.z],
rotation: [obj.rotation.x, obj.rotation.y, obj.rotation.z],
})
}
);
if (event) {
updateBackend(
@@ -299,7 +363,7 @@ function MoveControls({ movedObjects, setMovedObjects, itemsGroupRef, copiedObje
itemsData.current = [];
clearSelection();
}
};
const clearSelection = () => {
selectionGroup.current.children = [];
@@ -310,10 +374,15 @@ function MoveControls({ movedObjects, setMovedObjects, itemsGroupRef, copiedObje
setMovedObjects([]);
setRotatedObjects([]);
setSelectedAssets([]);
setKeyEvent("")
setKeyEvent("");
};
return (
<DistanceFindingControls
boundingBoxRef={boundingBoxRef}
object={movedObjects.length}
/>
);
}
return <DistanceFindingControls boundingBoxRef={boundingBoxRef} />;
}
export default MoveControls
export default MoveControls;

View File

@@ -205,7 +205,7 @@ const SelectionControls: React.FC = () => {
const email = localStorage.getItem("email");
const organization = email!.split("@")[1].split(".")[0];
const storedItems = JSON.parse(localStorage.getItem("FloorItems") || "[]");
const storedItems = JSON.parse(localStorage.getItem("FloorItems") ?? "[]");
const selectedUUIDs = selectedAssets.map((mesh: THREE.Object3D) => mesh.uuid);
const updatedStoredItems = storedItems.filter((item: { modelUuid: string }) => !selectedUUIDs.includes(item.modelUuid));

View File

@@ -1,6 +1,6 @@
import RoboticArmInstance from "./armInstance/roboticArmInstance";
import { useArmBotStore } from "../../../../store/simulation/useArmBotStore";
import RoboticArmContentUi from "../../ui3d/RoboticArmContentUi";
// import RoboticArmContentUi from "../../ui3d/RoboticArmContentUi";
import React from "react";
function RoboticArmInstances() {
@@ -11,7 +11,7 @@ function RoboticArmInstances() {
{armBots?.map((robot: ArmBotStatus) => (
<React.Fragment key={robot.modelUuid}>
<RoboticArmInstance armBot={robot} />
<RoboticArmContentUi roboticArm={robot} />
{/* <RoboticArmContentUi roboticArm={robot} /> */}
</React.Fragment>
))}
</>

View File

@@ -38,7 +38,12 @@ export default function PolygonGenerator({
turf.lineString(line.map((p: any) => p?.position))
);
const polygons = turf.polygonize(turf.featureCollection(lineFeatures));
const validLineFeatures = lineFeatures.filter((line) => {
const coords = line.geometry.coordinates;
return coords.length >= 2;
});
const polygons = turf.polygonize(turf.featureCollection(validLineFeatures));
renderWallGeometry(wallPoints);