Files
Dwinzo_dev/app/src/modules/builder/agv/pathNavigator.tsx

481 lines
13 KiB
TypeScript
Raw Normal View History

2025-04-10 17:46:11 +05:30
import React, { useEffect, useState, useRef, useMemo } from "react";
2025-03-26 18:28:14 +05:30
import * as THREE from "three";
2025-04-02 19:12:14 +05:30
import { useFrame, useThree } from "@react-three/fiber";
2025-03-26 18:28:14 +05:30
import { NavMeshQuery } from "@recast-navigation/core";
import { Line } from "@react-three/drei";
2025-04-15 18:34:38 +05:30
import {
useAnimationPlaySpeed,
usePlayButtonStore,
} from "../../../store/usePlayButtonStore";
2025-04-10 10:21:24 +05:30
import { usePlayAgv } from "../../../store/store";
2025-03-26 18:28:14 +05:30
interface PathNavigatorProps {
2025-04-10 10:21:24 +05:30
navMesh: any;
pathPoints: any;
id: string;
speed: number;
2025-04-15 18:34:38 +05:30
globalSpeed: number;
2025-04-10 10:21:24 +05:30
bufferTime: number;
hitCount: number;
processes: any[];
agvRef: any;
2025-04-10 17:46:11 +05:30
MaterialRef: any;
}
2025-04-10 10:21:24 +05:30
interface AGVData {
processId: string;
vehicleId: string;
hitCount: number;
totalHits: number;
}
type Phase = "initial" | "toDrop" | "toPickup";
2025-04-10 17:46:11 +05:30
type MaterialType = "Box" | "Crate";
export default function PathNavigator({
2025-04-10 10:21:24 +05:30
navMesh,
pathPoints,
id,
speed,
2025-04-11 18:08:53 +05:30
globalSpeed,
2025-04-10 10:21:24 +05:30
bufferTime,
hitCount,
processes,
agvRef,
2025-04-10 17:46:11 +05:30
MaterialRef,
}: PathNavigatorProps) {
2025-04-10 10:21:24 +05:30
const [currentPhase, setCurrentPhase] = useState<Phase>("initial");
const [path, setPath] = useState<[number, number, number][]>([]);
2025-04-15 18:34:38 +05:30
const [toPickupPath, setToPickupPath] = useState<[number, number, number][]>(
[]
);
const [pickupDropPath, setPickupDropPath] = useState<
[number, number, number][]
>([]);
const [dropPickupPath, setDropPickupPath] = useState<
[number, number, number][]
>([]);
const [initialPosition, setInitialPosition] = useState<THREE.Vector3 | null>(
null
);
const [initialRotation, setInitialRotation] = useState<THREE.Euler | null>(
null
);
2025-04-10 17:46:11 +05:30
const [boxVisible, setBoxVisible] = useState(false);
2025-04-10 10:21:24 +05:30
const distancesRef = useRef<number[]>([]);
const totalDistanceRef = useRef(0);
const progressRef = useRef(0);
const isWaiting = useRef(false);
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
const hasStarted = useRef(false);
2025-04-11 17:52:07 +05:30
const hasReachedPickup = useRef(false);
2025-04-10 10:21:24 +05:30
const { scene } = useThree();
const { isPlaying } = usePlayButtonStore();
const { PlayAgv, setPlayAgv } = usePlayAgv();
2025-04-11 17:52:07 +05:30
const boxRef = useRef<THREE.Mesh | null>(null);
2025-04-15 18:34:38 +05:30
const baseMaterials = useMemo(
() => ({
Box: new THREE.MeshStandardMaterial({ color: 0x8b4513 }),
Crate: new THREE.MeshStandardMaterial({ color: 0x00ff00 }),
Default: new THREE.MeshStandardMaterial({ color: 0xcccccc }),
}),
[]
);
2025-04-11 17:52:07 +05:30
2025-04-10 10:21:24 +05:30
useEffect(() => {
const object = scene.getObjectByProperty("uuid", id);
if (object) {
setInitialPosition(object.position.clone());
setInitialRotation(object.rotation.clone());
}
}, [scene, id]);
const computePath = (start: any, end: any) => {
try {
const navMeshQuery = new NavMeshQuery(navMesh);
const { path: segmentPath } = navMeshQuery.computePath(start, end);
return (
segmentPath?.map(
({ x, y, z }) => [x, y + 0.1, z] as [number, number, number]
) || []
);
} catch {
return [];
}
};
const resetState = () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
setPath([]);
setCurrentPhase("initial");
2025-04-11 17:52:07 +05:30
setToPickupPath([]);
2025-04-10 10:21:24 +05:30
setPickupDropPath([]);
setDropPickupPath([]);
2025-04-11 17:52:07 +05:30
setBoxVisible(false);
2025-04-10 10:21:24 +05:30
distancesRef.current = [];
totalDistanceRef.current = 0;
progressRef.current = 0;
isWaiting.current = false;
2025-04-11 17:52:07 +05:30
hasStarted.current = false;
hasReachedPickup.current = false;
2025-04-10 10:21:24 +05:30
if (initialPosition && initialRotation) {
const object = scene.getObjectByProperty("uuid", id);
if (object) {
object.position.copy(initialPosition);
object.rotation.copy(initialRotation);
}
}
};
useEffect(() => {
if (!isPlaying) {
resetState();
}
if (!navMesh || pathPoints.length < 2) return;
const [pickup, drop] = pathPoints.slice(-2);
2025-04-10 17:46:11 +05:30
2025-04-10 10:21:24 +05:30
const object = scene.getObjectByProperty("uuid", id);
if (!object) return;
2025-04-11 17:52:07 +05:30
const currentPosition = object.position;
2025-04-10 10:21:24 +05:30
const toPickupPath = computePath(currentPosition, pickup);
const pickupToDropPath = computePath(pickup, drop);
const dropToPickupPath = computePath(drop, pickup);
2025-04-15 18:34:38 +05:30
if (
toPickupPath.length &&
pickupToDropPath.length &&
dropToPickupPath.length
) {
2025-04-10 10:21:24 +05:30
setPickupDropPath(pickupToDropPath);
setDropPickupPath(dropToPickupPath);
setToPickupPath(toPickupPath);
setPath(toPickupPath);
setCurrentPhase("initial");
}
}, [navMesh, pathPoints, hitCount, isPlaying, PlayAgv]);
useEffect(() => {
if (path.length < 2) return;
let total = 0;
const segmentDistances = path.slice(0, -1).map((point, i) => {
const dist = new THREE.Vector3(...point).distanceTo(
new THREE.Vector3(...path[i + 1])
);
total += dist;
return dist;
});
distancesRef.current = segmentDistances;
totalDistanceRef.current = total;
progressRef.current = 0;
isWaiting.current = false;
}, [path]);
2025-04-11 17:52:07 +05:30
function logAgvStatus(id: string, status: string) {
2025-04-15 18:34:38 +05:30
// console.log(
// `AGV ${id}: ${status}`
2025-04-15 18:34:38 +05:30
// );
2025-04-11 17:52:07 +05:30
}
2025-04-10 17:46:11 +05:30
function findProcessByTargetModelUUID(processes: any, targetModelUUID: any) {
for (const process of processes) {
for (const path of process.paths) {
for (const point of path.points) {
if (
point.connections?.targets?.some(
(target: any) => target.modelUUID === targetModelUUID
)
) {
2025-04-11 17:52:07 +05:30
return process.id;
2025-04-10 17:46:11 +05:30
}
}
}
}
2025-04-11 17:52:07 +05:30
return null;
2025-04-10 17:46:11 +05:30
}
useEffect(() => {
2025-04-11 17:52:07 +05:30
if (!scene || !boxRef || !processes || !MaterialRef.current) return;
2025-04-10 17:46:11 +05:30
const existingObject = scene.getObjectByProperty("uuid", id);
if (!existingObject) return;
2025-04-11 17:52:07 +05:30
if (boxRef.current?.parent) {
boxRef.current.parent.remove(boxRef.current);
boxRef.current = null;
}
2025-04-10 17:46:11 +05:30
if (boxVisible) {
const matchedProcess = findProcessByTargetModelUUID(processes, id);
2025-04-11 17:52:07 +05:30
let materialType: "Box" | "Crate" | "Default" = "Default";
2025-04-10 17:46:11 +05:30
if (matchedProcess) {
const materialEntry = MaterialRef.current.find((item: any) =>
item.objects.some((obj: any) => obj.processId === matchedProcess)
);
if (materialEntry) {
2025-04-11 17:52:07 +05:30
materialType = materialEntry.material;
2025-04-10 17:46:11 +05:30
}
}
const boxGeometry = new THREE.BoxGeometry(0.5, 0.5, 0.5);
2025-04-11 17:52:07 +05:30
const boxMesh = new THREE.Mesh(boxGeometry, baseMaterials[materialType]);
2025-04-10 17:46:11 +05:30
boxMesh.position.y = 1;
boxMesh.name = `box-${id}`;
existingObject.add(boxMesh);
boxRef.current = boxMesh;
}
return () => {
if (boxRef.current?.parent) {
boxRef.current.parent.remove(boxRef.current);
}
};
2025-04-11 17:52:07 +05:30
}, [processes, MaterialRef, boxVisible, scene, id, baseMaterials]);
2025-04-10 10:21:24 +05:30
useFrame((_, delta) => {
2025-04-15 18:34:38 +05:30
const currentAgv = (agvRef.current || []).find(
(agv: AGVData) => agv.vehicleId === id
);
2025-04-10 10:21:24 +05:30
if (!scene || !id || !isPlaying) return;
const object = scene.getObjectByProperty("uuid", id);
if (!object) return;
if (isPlaying && !hasStarted.current) {
hasStarted.current = false;
progressRef.current = 0;
isWaiting.current = false;
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
}
const isAgvReady = () => {
if (!agvRef.current || agvRef.current.length === 0) return false;
if (!currentAgv) return false;
2025-04-15 18:34:38 +05:30
2025-04-11 17:52:07 +05:30
return currentAgv.isActive && hitCount >= currentAgv.maxHitCount;
2025-04-10 10:21:24 +05:30
};
if (isPlaying && !hasStarted.current && toPickupPath.length > 0) {
2025-04-10 17:46:11 +05:30
setBoxVisible(false);
2025-04-10 10:21:24 +05:30
const startPoint = new THREE.Vector3(...toPickupPath[0]);
object.position.copy(startPoint);
if (toPickupPath.length > 1) {
const nextPoint = new THREE.Vector3(...toPickupPath[1]);
const direction = nextPoint.clone().sub(startPoint).normalize();
object.rotation.y = Math.atan2(direction.x, direction.z);
}
hasStarted.current = true;
progressRef.current = 0;
2025-04-11 17:52:07 +05:30
hasReachedPickup.current = false;
2025-04-10 17:46:11 +05:30
setToPickupPath(toPickupPath.slice(-1));
2025-04-11 17:52:07 +05:30
logAgvStatus(id, "Started from station, heading to pickup");
2025-04-10 10:21:24 +05:30
return;
}
2025-04-11 17:52:07 +05:30
if (isPlaying && currentPhase === "initial" && !hasReachedPickup.current) {
2025-04-15 18:34:38 +05:30
const reached = moveAlongPath(
object,
path,
distancesRef.current,
speed,
delta,
progressRef
);
2025-04-10 10:21:24 +05:30
2025-04-11 17:52:07 +05:30
if (reached) {
hasReachedPickup.current = true;
if (currentAgv) {
2025-04-15 18:34:38 +05:30
currentAgv.status = "picking";
2025-04-11 17:52:07 +05:30
}
logAgvStatus(id, "Reached pickup point, Waiting for material");
}
2025-04-10 10:21:24 +05:30
return;
}
2025-04-11 17:52:07 +05:30
if (isPlaying && currentAgv?.isActive && currentPhase === "initial") {
if (!isAgvReady()) return;
setTimeout(() => {
setBoxVisible(true);
setPath([...pickupDropPath]);
setCurrentPhase("toDrop");
progressRef.current = 0;
logAgvStatus(id, "Started from pickup point, heading to drop point");
if (currentAgv) {
2025-04-15 18:34:38 +05:30
currentAgv.status = "toDrop";
2025-04-11 17:52:07 +05:30
}
2025-04-15 18:34:38 +05:30
}, 0);
2025-04-11 17:52:07 +05:30
return;
}
2025-04-10 10:21:24 +05:30
2025-04-11 17:52:07 +05:30
if (isPlaying && currentPhase === "toDrop") {
2025-04-15 18:34:38 +05:30
const reached = moveAlongPath(
object,
path,
distancesRef.current,
speed,
delta,
progressRef
);
2025-04-10 10:21:24 +05:30
2025-04-11 17:52:07 +05:30
if (reached && !isWaiting.current) {
isWaiting.current = true;
logAgvStatus(id, "Reached drop point");
if (currentAgv) {
2025-04-15 18:34:38 +05:30
currentAgv.status = "droping";
currentAgv.hitCount = currentAgv.hitCount--;
2025-04-11 17:52:07 +05:30
}
timeoutRef.current = setTimeout(() => {
setPath([...dropPickupPath]);
setCurrentPhase("toPickup");
progressRef.current = 0;
isWaiting.current = false;
setBoxVisible(false);
if (currentAgv) {
2025-04-15 18:34:38 +05:30
currentAgv.status = "toPickup";
2025-04-11 17:52:07 +05:30
}
2025-04-15 18:34:38 +05:30
logAgvStatus(
id,
"Started from droping point, heading to pickup point"
);
2025-04-11 17:52:07 +05:30
}, bufferTime * 1000);
2025-04-10 10:21:24 +05:30
}
2025-04-11 17:52:07 +05:30
return;
2025-04-10 10:21:24 +05:30
}
2025-04-11 17:52:07 +05:30
if (isPlaying && currentPhase === "toPickup") {
2025-04-15 18:34:38 +05:30
const reached = moveAlongPath(
object,
path,
distancesRef.current,
speed,
delta,
progressRef
);
2025-04-10 10:21:24 +05:30
2025-04-11 17:52:07 +05:30
if (reached) {
if (currentAgv) {
currentAgv.isActive = false;
2025-04-10 10:21:24 +05:30
}
2025-04-11 17:52:07 +05:30
setCurrentPhase("initial");
if (currentAgv) {
2025-04-15 18:34:38 +05:30
currentAgv.status = "picking";
2025-04-11 17:52:07 +05:30
}
logAgvStatus(id, "Reached pickup point again, cycle complete");
}
return;
}
2025-04-10 10:21:24 +05:30
2025-04-15 18:34:38 +05:30
moveAlongPath(
object,
path,
distancesRef.current,
speed,
delta,
progressRef
);
2025-04-11 17:52:07 +05:30
});
2025-04-10 17:46:11 +05:30
2025-04-11 17:52:07 +05:30
function moveAlongPath(
object: THREE.Object3D,
path: [number, number, number][],
distances: number[],
speed: number,
delta: number,
progressRef: React.MutableRefObject<number>
): boolean {
if (path.length < 2) return false;
2025-04-10 17:46:11 +05:30
2025-04-11 18:08:53 +05:30
progressRef.current += delta * (speed * globalSpeed);
2025-04-11 17:52:07 +05:30
let covered = progressRef.current;
let accumulated = 0;
let index = 0;
2025-04-10 10:21:24 +05:30
2025-04-11 17:52:07 +05:30
for (; index < distances.length; index++) {
const dist = distances[index];
if (accumulated + dist >= covered) break;
accumulated += dist;
}
2025-04-10 10:21:24 +05:30
2025-04-11 17:52:07 +05:30
if (index >= path.length - 1) {
if (path.length > 1) {
const lastDirection = new THREE.Vector3(...path[path.length - 1])
.sub(new THREE.Vector3(...path[path.length - 2]))
.normalize();
object.rotation.y = Math.atan2(lastDirection.x, lastDirection.z);
}
return true;
2025-04-10 10:21:24 +05:30
}
const start = new THREE.Vector3(...path[index]);
const end = new THREE.Vector3(...path[index + 1]);
2025-04-11 17:52:07 +05:30
const dist = distances[index];
2025-04-10 10:21:24 +05:30
const t = THREE.MathUtils.clamp((covered - accumulated) / dist, 0, 1);
object.position.copy(start.clone().lerp(end, t));
2025-04-11 17:52:07 +05:30
if (dist > 0.1) {
const targetDirection = end.clone().sub(start).normalize();
const targetRotationY = Math.atan2(targetDirection.x, targetDirection.z);
const rotationSpeed = Math.min(5 * delta, 1);
2025-04-15 18:34:38 +05:30
object.rotation.y = THREE.MathUtils.lerp(
object.rotation.y,
targetRotationY,
rotationSpeed
);
2025-04-11 17:52:07 +05:30
}
return false;
}
2025-04-10 10:21:24 +05:30
useEffect(() => {
return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
};
}, []);
return (
<group name="path-navigator-lines">
2025-04-10 10:21:24 +05:30
{toPickupPath.length > 0 && (
<Line
points={toPickupPath}
color="blue"
lineWidth={3}
dashed
dashSize={0.75}
dashScale={2}
/>
)}
{pickupDropPath.length > 0 && (
<Line points={pickupDropPath} color="red" lineWidth={3} />
)}
{dropPickupPath.length > 0 && (
<Line points={dropPickupPath} color="red" lineWidth={3} />
)}
</group>
);
}