"updated single flow"

This commit is contained in:
SreeNath14
2025-04-10 17:46:11 +05:30
94 changed files with 6519 additions and 3372 deletions

View File

@@ -18,18 +18,21 @@ type PathPoints = {
interface ProcessContainerProps {
processes: any[];
agvRef: any;
MaterialRef: any;
}
const Agv: React.FC<ProcessContainerProps> = ({ processes, agvRef }) => {
const Agv: React.FC<ProcessContainerProps> = ({
processes,
agvRef,
MaterialRef,
}) => {
const [pathPoints, setPathPoints] = useState<PathPoints[]>([]);
const { simulationStates } = useSimulationStates();
const { navMesh } = useNavMesh();
const { isPlaying } = usePlayButtonStore();
const { PlayAgv, setPlayAgv } = usePlayAgv();
useEffect(() => {
console.log("agvRef: ", agvRef);
}, [agvRef]);
useEffect(() => {
if (simulationStates.length > 0) {
@@ -90,6 +93,7 @@ const Agv: React.FC<ProcessContainerProps> = ({ processes, agvRef }) => {
hitCount={pair.hitCount}
processes={processes}
agvRef={agvRef}
MaterialRef={MaterialRef}
/>
{pair.points.slice(1).map((point, idx) => (

View File

@@ -32,7 +32,7 @@ export default function NavMeshDetails({
const [positions, indices] = getPositionsAndIndices(meshes);
const cellSize = 0.35;
const cellSize = 0.2;
const cellHeight = 0.7;
const walkableRadius = 0.5;
const { success, navMesh } = generateSoloNavMesh(positions, indices, {

View File

@@ -1,10 +1,11 @@
import React, { useEffect, useState, useRef } from "react";
import React, { useEffect, useState, useRef, useMemo } from "react";
import * as THREE from "three";
import { useFrame, useThree } from "@react-three/fiber";
import { NavMeshQuery } from "@recast-navigation/core";
import { Line } from "@react-three/drei";
import { usePlayButtonStore } from "../../../store/usePlayButtonStore";
import { usePlayAgv } from "../../../store/store";
import crate from "../../../assets/gltf-glb/crate_box.glb";
interface PathNavigatorProps {
navMesh: any;
@@ -15,6 +16,7 @@ interface PathNavigatorProps {
hitCount: number;
processes: any[];
agvRef: any;
MaterialRef: any;
}
interface AGVData {
processId: string;
@@ -23,7 +25,7 @@ interface AGVData {
totalHits: number;
}
type Phase = "initial" | "toDrop" | "toPickup";
type MaterialType = "Box" | "Crate";
export default function PathNavigator({
navMesh,
pathPoints,
@@ -33,11 +35,13 @@ export default function PathNavigator({
hitCount,
processes,
agvRef,
MaterialRef,
}: PathNavigatorProps) {
const [currentPhase, setCurrentPhase] = useState<Phase>("initial");
// console.log('agvRef: ', agvRef);
//
const [path, setPath] = useState<[number, number, number][]>([]);
const PickUpDrop = useRef([]);
// const [currentPhase, setCurrentPhase] = useState<"initial" | "loop">(
// "initial"
@@ -45,6 +49,7 @@ export default function PathNavigator({
const [toPickupPath, setToPickupPath] = useState<[number, number, number][]>(
[]
);
const [pickupDropPath, setPickupDropPath] = useState<
[number, number, number][]
>([]);
@@ -57,6 +62,7 @@ export default function PathNavigator({
const [initialRotation, setInitialRotation] = useState<THREE.Euler | null>(
null
);
const [boxVisible, setBoxVisible] = useState(false);
const distancesRef = useRef<number[]>([]);
const totalDistanceRef = useRef(0);
@@ -123,6 +129,9 @@ export default function PathNavigator({
if (!navMesh || pathPoints.length < 2) return;
const [pickup, drop] = pathPoints.slice(-2);
PickUpDrop.current = pathPoints.slice(-2);
const object = scene.getObjectByProperty("uuid", id);
if (!object) return;
@@ -171,13 +180,101 @@ export default function PathNavigator({
// Add these refs outside the useFrame if not already present:
const startPointReached = useRef(false);
const baseMaterials = useMemo(
() => ({
Box: new THREE.MeshStandardMaterial({ color: 0x8b4513 }),
Crate: new THREE.MeshStandardMaterial({ color: 0x00ff00 }),
// Default: new THREE.MeshStandardMaterial({ color: 0x00ff00 }),
Default: new THREE.MeshStandardMaterial(),
}),
[]
);
// Example usage:
const targetModelUUID = id; // Replace with your target ID
const matchedProcess = findProcessByTargetModelUUID(
processes,
targetModelUUID
);
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
)
) {
//
return process.id; // Return the process if a match is found
}
}
}
}
return null; // Return null if no match is found
}
useFrame((_, delta) => {});
const boxRef = useRef<THREE.Mesh | null>(null);
useEffect(() => {
if (!scene || !boxRef || !processes) return;
// 1. Find the existing object by UUID
const existingObject = scene.getObjectByProperty("uuid", id);
if (!existingObject) return;
// 2. Find the process that targets this object's modelUUID
if (boxVisible) {
const matchedProcess = findProcessByTargetModelUUID(processes, id);
// 3. Determine the material (from materialref) if a process is matched
let materialType = "Default";
if (matchedProcess) {
const materialEntry = MaterialRef.current.find((item: any) =>
item.objects.some((obj: any) => obj.processId === matchedProcess)
);
console.log("materialEntry: ", materialEntry);
if (materialEntry) {
materialType = materialEntry.material; // "Box" or "Crate"
}
}
// 4. Create the box mesh with the assigned material
const boxGeometry = new THREE.BoxGeometry(0.5, 0.5, 0.5);
const boxMaterial = baseMaterials[materialType as MaterialType];
const boxMesh = new THREE.Mesh(boxGeometry, boxMaterial);
boxMesh.position.y = 1;
boxMesh.name = `box-${id}`;
// 5. Add to scene and cleanup
existingObject.add(boxMesh);
boxRef.current = boxMesh;
}
if (!startPointReached.current && boxVisible) {
setBoxVisible(false);
}
return () => {
if (boxRef.current?.parent) {
boxRef.current.parent.remove(boxRef.current);
}
boxRef.current = null;
};
}, [
processes,
MaterialRef,
boxVisible,
findProcessByTargetModelUUID,
startPointReached,
]);
useFrame((_, delta) => {
const currentAgv = (agvRef.current || []).find(
(agv: AGVData) => agv.vehicleId === id
);
console.log("currentAgv: ", currentAgv?.isplaying);
if (!scene || !id || !isPlaying) return;
@@ -203,6 +300,7 @@ export default function PathNavigator({
// Step 1: Snap to start point on first play
if (isPlaying && !hasStarted.current && toPickupPath.length > 0) {
setBoxVisible(false);
const startPoint = new THREE.Vector3(...toPickupPath[0]);
object.position.copy(startPoint);
@@ -216,23 +314,23 @@ export default function PathNavigator({
startPointReached.current = true;
progressRef.current = 0;
setToPickupPath(toPickupPath.slice(-1));
return;
}
// Step 2: Wait at start point for AGV readiness (only if expected hit count is not met)
if (
isPlaying &&
startPointReached.current &&
path.length === 0 &&
currentAgv?.isplaying
) {
// Step 2: Wait at start point for AGV readiness
if (isPlaying && startPointReached.current && path.length === 0) {
if (!isAgvReady()) {
return; // Prevent transitioning to the next phase if AGV is not ready
}
setBoxVisible(true);
setPath([...toPickupPath]); // Start path transition once the AGV is ready
setCurrentPhase("toDrop");
progressRef.current = 0;
console.log("startPointReached: ", startPointReached.current);
startPointReached.current = false;
return;
@@ -283,12 +381,44 @@ export default function PathNavigator({
if (currentPhase === "toDrop") {
nextPath = dropPickupPath;
nextPhase = "toPickup";
setBoxVisible(false);
} else if (currentPhase === "toPickup") {
nextPath = pickupDropPath;
nextPhase = "toDrop";
// When returning to start point (toPickup phase completed)
// Set position to toPickupPath[1] instead of [0]
if (toPickupPath.length > 1) {
object.position.copy(new THREE.Vector3(...toPickupPath[1]));
// Also set rotation towards the next point if available
if (toPickupPath.length > 2) {
const nextPoint = new THREE.Vector3(...toPickupPath[2]);
const direction = nextPoint
.clone()
.sub(object.position)
.normalize();
object.rotation.y = Math.atan2(direction.x, direction.z);
}
}
// Reset the path and mark start point as reached
setPath([]);
startPointReached.current = true;
progressRef.current = 0;
distancesRef.current = [];
// Stop the AGV by setting isplaying to false
if (currentAgv) {
currentAgv.isplaying = false;
}
// Clear timeout and return to prevent further movement
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
return;
} else {
nextPath = pickupDropPath;
nextPhase = "toDrop";
setBoxVisible(true);
}
setPath([...nextPath]);
@@ -297,28 +427,12 @@ export default function PathNavigator({
isWaiting.current = false;
distancesRef.current = [];
// Decrease the expected count if AGV is ready and has completed its path
if (currentAgv) {
currentAgv.expectedCount = Math.max(0, currentAgv.expectedCount - 1); // Decrease but ensure it's not negative
console.log(
"Decreased expected count to: ",
currentAgv.expectedCount
);
}
// Reset hit count for the next cycle
if (agvRef.current) {
agvRef.current = agvRef.current.map((agv: AGVData) =>
agv.vehicleId === id ? { ...agv, hitCount: null } : agv
agv.vehicleId === id ? { ...agv, hitCount: 0 } : agv
);
}
// 🔁 Reset and wait again after reaching start
if (currentPhase === "toPickup" && currentAgv) {
currentAgv.isplaying = false;
setPath([]);
startPointReached.current = true;
progressRef.current = 0;
}
}, bufferTime * 1000);
return;

View File

@@ -1,6 +1,6 @@
import * as THREE from "three";
import { Geometry, Base, Subtraction } from "@react-three/csg";
import { useDeleteModels } from "../../../store/store";
import { useDeleteTool } from "../../../store/store";
import { useRef } from "react";
export interface CsgProps {
@@ -11,19 +11,19 @@ export interface CsgProps {
}
export const Csg: React.FC<CsgProps> = (props) => {
const { deleteModels } = useDeleteModels();
const { deleteTool } = useDeleteTool();
const modelRef = useRef<THREE.Object3D>();
const originalMaterials = useRef<Map<THREE.Mesh, THREE.Material>>(new Map());
const handleHover = (hovered: boolean, object: THREE.Mesh | null) => {
if (modelRef.current && deleteModels) {
if (modelRef.current && deleteTool) {
modelRef.current.traverse((child) => {
if (child instanceof THREE.Mesh) {
if (!originalMaterials.current.has(child)) {
originalMaterials.current.set(child, child.material);
}
child.material = child.material.clone();
child.material.color.set(hovered && deleteModels ? 0xff0000 : (originalMaterials.current.get(child) as any).color);
child.material.color.set(hovered && deleteTool ? 0xff0000 : (originalMaterials.current.get(child) as any).color);
}
});
}

View File

@@ -86,8 +86,8 @@ async function addAssetModel(
} else {
// console.log(`Added ${selectedItem.name} from Backend`);
loader.load(`${url_Backend_dwinzo}/api/v1/AssetFile/${selectedItem.id}`, async (gltf) => {
const modelBlob = await fetch(`${url_Backend_dwinzo}/api/v1/AssetFile/${selectedItem.id}`).then((res) => res.blob());
loader.load(`${url_Backend_dwinzo}/api/v2/AssetFile/${selectedItem.id}`, async (gltf) => {
const modelBlob = await fetch(`${url_Backend_dwinzo}/api/v2/AssetFile/${selectedItem.id}`).then((res) => res.blob());
await storeGLTF(selectedItem.id, modelBlob);
THREE.Cache.add(selectedItem.id, gltf);
await handleModelLoad(gltf, intersectPoint!, selectedItem, itemsGroup, tempLoader, isTempLoader, setFloorItems, setSimulationStates, socket);
@@ -220,7 +220,7 @@ async function handleModelLoad(
eventData.position = newFloorItem.position;
eventData.rotation = [model.rotation.x, model.rotation.y, model.rotation.z];
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema)[]) => [
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | Types.ArmBotEventsSchema)[]) => [
...(prevEvents || []),
eventData as Types.ConveyorEventsSchema
]);
@@ -237,6 +237,7 @@ async function handleModelLoad(
points: {
uuid: pointUUID,
position: res.points.position as [number, number, number],
rotation: res.points.rotation as [number, number, number],
actions: { uuid: THREE.MathUtils.generateUUID(), name: 'Action 1', type: '', start: {}, hitCount: 1, end: {}, buffer: 0 },
connections: { source: { modelUUID: model.uuid, pointUUID: pointUUID }, targets: [] },
speed: 2,
@@ -283,13 +284,141 @@ async function handleModelLoad(
return updatedItems;
});
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema)[]) => [
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | Types.ArmBotEventsSchema)[]) => [
...(prevEvents || []),
eventData as Types.VehicleEventsSchema
]);
socket.emit("v2:model-asset:add", data);
} else if (res.type === "StaticMachine") {
const pointUUID = THREE.MathUtils.generateUUID();
const backendEventData: Extract<Types.EventData['eventData'], { type: 'StaticMachine' }> = {
type: "StaticMachine",
points: {
uuid: pointUUID,
position: res.points.position as [number, number, number],
rotation: res.points.rotation as [number, number, number],
actions: { uuid: THREE.MathUtils.generateUUID(), name: 'Action 1', buffer: 0, material: 'Inherit' },
triggers: { uuid: THREE.MathUtils.generateUUID(), name: 'Trigger 1', type: 'OnComplete' },
connections: { source: { modelUUID: model.uuid, pointUUID: pointUUID }, targets: [] },
}
}
// API
// await setFloorItemApi(
// organization,
// newFloorItem.modeluuid,
// newFloorItem.modelname,
// newFloorItem.modelfileID,
// newFloorItem.position,
// { x: model.rotation.x, y: model.rotation.y, z: model.rotation.z },
// false,
// true,
// { type: backendEventData.type, points: backendEventData.points }
// );
// SOCKET
const data = {
organization,
modeluuid: newFloorItem.modeluuid,
modelname: newFloorItem.modelname,
modelfileID: newFloorItem.modelfileID,
position: newFloorItem.position,
rotation: { x: model.rotation.x, y: model.rotation.y, z: model.rotation.z },
isLocked: false,
isVisible: true,
eventData: { type: backendEventData.type, points: backendEventData.points },
socketId: socket.id
};
const eventData: any = backendEventData;
eventData.modeluuid = newFloorItem.modeluuid;
eventData.modelName = newFloorItem.modelname;
eventData.position = newFloorItem.position;
eventData.rotation = [model.rotation.x, model.rotation.y, model.rotation.z];
setFloorItems((prevItems) => {
const updatedItems = [...(prevItems || []), newFloorItem];
localStorage.setItem("FloorItems", JSON.stringify(updatedItems));
return updatedItems;
});
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | Types.ArmBotEventsSchema)[]) => [
...(prevEvents || []),
eventData as Types.StaticMachineEventsSchema
]);
socket.emit("v2:model-asset:add", data);
} else if (res.type === "ArmBot") {
const pointUUID = THREE.MathUtils.generateUUID();
const backendEventData: Extract<Types.EventData['eventData'], { type: 'ArmBot' }> = {
type: "ArmBot",
points: {
uuid: pointUUID,
position: res.points.position as [number, number, number],
rotation: res.points.rotation as [number, number, number],
actions: { uuid: THREE.MathUtils.generateUUID(), name: 'Action 1', speed: 1, processes: [] },
triggers: { uuid: THREE.MathUtils.generateUUID(), name: 'Trigger 1', type: 'OnComplete' },
connections: { source: { modelUUID: model.uuid, pointUUID: pointUUID }, targets: [] },
}
}
// API
// await setFloorItemApi(
// organization,
// newFloorItem.modeluuid,
// newFloorItem.modelname,
// newFloorItem.modelfileID,
// newFloorItem.position,
// { x: model.rotation.x, y: model.rotation.y, z: model.rotation.z },
// false,
// true,
// { type: backendEventData.type, points: backendEventData.points }
// );
// SOCKET
const data = {
organization,
modeluuid: newFloorItem.modeluuid,
modelname: newFloorItem.modelname,
modelfileID: newFloorItem.modelfileID,
position: newFloorItem.position,
rotation: { x: model.rotation.x, y: model.rotation.y, z: model.rotation.z },
isLocked: false,
isVisible: true,
eventData: { type: backendEventData.type, points: backendEventData.points },
socketId: socket.id
};
const eventData: any = backendEventData;
eventData.modeluuid = newFloorItem.modeluuid;
eventData.modelName = newFloorItem.modelname;
eventData.position = newFloorItem.position;
eventData.rotation = [model.rotation.x, model.rotation.y, model.rotation.z];
setFloorItems((prevItems) => {
const updatedItems = [...(prevItems || []), newFloorItem];
localStorage.setItem("FloorItems", JSON.stringify(updatedItems));
return updatedItems;
});
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | Types.ArmBotEventsSchema)[]) => [
...(prevEvents || []),
eventData as Types.ArmBotEventsSchema
]);
socket.emit("v2:model-asset:add", data);
} else {
// API

View File

@@ -53,7 +53,7 @@ export default async function assetManager(
if (!activePromises.get(taskId)) return; // Stop processing if task is canceled
await new Promise<void>(async (resolve) => {
const modelUrl = `${url_Backend_dwinzo}/api/v1/AssetFile/${item.modelfileID!}`;
const modelUrl = `${url_Backend_dwinzo}/api/v2/AssetFile/${item.modelfileID!}`;
// Check Three.js Cache
const cachedModel = THREE.Cache.get(item.modelfileID!);

View File

@@ -53,7 +53,7 @@ export default function addFloorToScene(
const mesh = new THREE.Mesh(geometry, material);
mesh.receiveShadow = true;
mesh.position.y = layer;
mesh.position.y = (layer) * CONSTANTS.wallConfig.height;
mesh.rotateX(Math.PI / 2);
mesh.name = `Floor_Layer_${layer}`;

View File

@@ -171,7 +171,7 @@ function loadOnlyFloors(
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.position.y = (floor[0][0][2] - 1) * CONSTANTS.wallConfig.height + 0.03;
mesh.position.y = (floor[0][0][2] - 1) * CONSTANTS.wallConfig.height;
mesh.rotateX(Math.PI / 2);
mesh.name = `Only_Floor_Line_${floor[0][0][2]}`;

View File

@@ -1,143 +1,143 @@
import { useEffect, useState } from "react";
import { getLines } from "../../../../services/factoryBuilder/lines/getLinesApi";
import * as THREE from "three";
import {
useActiveLayer,
useDeletedLines,
useNewLines,
useToggleView,
} from "../../../../store/store";
import objectLinesToArray from "./lineConvertions/objectLinesToArray";
import { Html } from "@react-three/drei";
import * as Types from "../../../../types/world/worldTypes";
const DistanceText = () => {
const [lines, setLines] = useState<
{
distance: string;
position: THREE.Vector3;
userData: Types.Line;
layer: string;
}[]
>([]);
const { activeLayer } = useActiveLayer();
const { toggleView } = useToggleView();
const { newLines, setNewLines } = useNewLines();
const { deletedLines, setDeletedLines } = useDeletedLines();
useEffect(() => {
const email = localStorage.getItem("email");
if (!email) return;
const organization = email.split("@")[1].split(".")[0];
getLines(organization).then((data) => {
data = objectLinesToArray(data);
const lines = data
.filter((line: Types.Line) => line[0][2] === activeLayer)
.map((line: Types.Line) => {
const point1 = new THREE.Vector3(
line[0][0].x,
line[0][0].y,
line[0][0].z
);
const point2 = new THREE.Vector3(
line[1][0].x,
line[1][0].y,
line[1][0].z
);
const distance = point1.distanceTo(point2);
const midpoint = new THREE.Vector3()
.addVectors(point1, point2)
.divideScalar(2);
return {
distance: distance.toFixed(1),
position: midpoint,
userData: line,
layer: activeLayer,
};
});
setLines(lines);
});
}, [activeLayer]);
useEffect(() => {
if (newLines.length > 0) {
if (newLines[0][0][2] !== activeLayer) return;
const newLinesData = newLines.map((line: Types.Line) => {
const point1 = new THREE.Vector3(
line[0][0].x,
line[0][0].y,
line[0][0].z
);
const point2 = new THREE.Vector3(
line[1][0].x,
line[1][0].y,
line[1][0].z
);
const distance = point1.distanceTo(point2);
const midpoint = new THREE.Vector3()
.addVectors(point1, point2)
.divideScalar(2);
return {
distance: distance.toFixed(1),
position: midpoint,
userData: line,
layer: activeLayer,
};
});
setLines((prevLines) => [...prevLines, ...newLinesData]);
setNewLines([]);
}
}, [newLines, activeLayer]);
useEffect(() => {
if ((deletedLines as Types.Lines).length > 0) {
setLines((prevLines) =>
prevLines.filter(
(line) =>
!deletedLines.some(
(deletedLine: any) =>
deletedLine[0][1] === line.userData[0][1] &&
deletedLine[1][1] === line.userData[1][1]
)
)
);
setDeletedLines([]);
}
}, [deletedLines]);
return (
<>
{toggleView && (
<group name="Distance_Text">
{lines.map((text) => (
<Html
// data
key={`${text.userData[0][1]}_${text.userData[1][1]}`}
userData={text.userData}
position={[text.position.x, 1, text.position.z]}
// class
wrapperClass="distance-text-wrapper"
className="distance-text"
// other
zIndexRange={[100, 0]}
prepend
sprite
>
<div
key={`${text.userData[0][1]}_${text.userData[1][1]}`}
className={`distance line-${text.userData[0][1]}_${text.userData[1][1]}_${text.layer}`}
>
{text.distance} m
</div>
</Html>
))}
</group>
)}
</>
);
};
export default DistanceText;
import { useEffect, useState } from "react";
import { getLines } from "../../../../../services/factoryBuilder/lines/getLinesApi";
import * as THREE from "three";
import {
useActiveLayer,
useDeletedLines,
useNewLines,
useToggleView,
} from "../../../../../store/store";
import objectLinesToArray from "../lineConvertions/objectLinesToArray";
import { Html } from "@react-three/drei";
import * as Types from "../../../../../types/world/worldTypes";
const DistanceText = () => {
const [lines, setLines] = useState<
{
distance: string;
position: THREE.Vector3;
userData: Types.Line;
layer: string;
}[]
>([]);
const { activeLayer } = useActiveLayer();
const { toggleView } = useToggleView();
const { newLines, setNewLines } = useNewLines();
const { deletedLines, setDeletedLines } = useDeletedLines();
useEffect(() => {
const email = localStorage.getItem("email");
if (!email) return;
const organization = email.split("@")[1].split(".")[0];
getLines(organization).then((data) => {
data = objectLinesToArray(data);
const lines = data
.filter((line: Types.Line) => line[0][2] === activeLayer)
.map((line: Types.Line) => {
const point1 = new THREE.Vector3(
line[0][0].x,
line[0][0].y,
line[0][0].z
);
const point2 = new THREE.Vector3(
line[1][0].x,
line[1][0].y,
line[1][0].z
);
const distance = point1.distanceTo(point2);
const midpoint = new THREE.Vector3()
.addVectors(point1, point2)
.divideScalar(2);
return {
distance: distance.toFixed(1),
position: midpoint,
userData: line,
layer: activeLayer,
};
});
setLines(lines);
});
}, [activeLayer]);
useEffect(() => {
if (newLines.length > 0) {
if (newLines[0][0][2] !== activeLayer) return;
const newLinesData = newLines.map((line: Types.Line) => {
const point1 = new THREE.Vector3(
line[0][0].x,
line[0][0].y,
line[0][0].z
);
const point2 = new THREE.Vector3(
line[1][0].x,
line[1][0].y,
line[1][0].z
);
const distance = point1.distanceTo(point2);
const midpoint = new THREE.Vector3()
.addVectors(point1, point2)
.divideScalar(2);
return {
distance: distance.toFixed(1),
position: midpoint,
userData: line,
layer: activeLayer,
};
});
setLines((prevLines) => [...prevLines, ...newLinesData]);
setNewLines([]);
}
}, [newLines, activeLayer]);
useEffect(() => {
if ((deletedLines as Types.Lines).length > 0) {
setLines((prevLines) =>
prevLines.filter(
(line) =>
!deletedLines.some(
(deletedLine: any) =>
deletedLine[0][1] === line.userData[0][1] &&
deletedLine[1][1] === line.userData[1][1]
)
)
);
setDeletedLines([]);
}
}, [deletedLines]);
return (
<>
{toggleView && (
<group name="Distance_Text">
{lines.map((text) => (
<Html
// data
key={`${text.userData[0][1]}_${text.userData[1][1]}`}
userData={text.userData}
position={[text.position.x, 1, text.position.z]}
// class
wrapperClass="distance-text-wrapper"
className="distance-text"
// other
zIndexRange={[1, 0]}
prepend
sprite
>
<div
key={`${text.userData[0][1]}_${text.userData[1][1]}`}
className={`distance line-${text.userData[0][1]}_${text.userData[1][1]}_${text.layer}`}
>
{text.distance} m
</div>
</Html>
))}
</group>
)}
</>
);
};
export default DistanceText;

View File

@@ -0,0 +1,71 @@
import * as THREE from "three";
import { Html } from "@react-three/drei";
import { useState, useEffect } from "react";
import { useActiveLayer } from "../../../../../store/store";
const ReferenceDistanceText = ({ line }: { line: any }) => {
interface TextState {
distance: string;
position: THREE.Vector3;
userData: any;
layer: any;
}
const [text, setTexts] = useState<TextState | null>(null);
const { activeLayer } = useActiveLayer();
useEffect(() => {
if (line) {
if (line.parent === null) {
setTexts(null);
return;
}
const distance = line.userData.linePoints.cursorPosition.distanceTo(
line.userData.linePoints.startPoint
);
const midpoint = new THREE.Vector3()
.addVectors(
line.userData.linePoints.cursorPosition,
line.userData.linePoints.startPoint
)
.divideScalar(2);
const newTexts = {
distance: distance.toFixed(1),
position: midpoint,
userData: line,
layer: activeLayer,
};
setTexts(newTexts);
}
});
return (
<group name="Reference_Distance_Text">
<mesh>
{text !== null && (
<Html
// data
key={text.distance}
userData={text.userData}
position={[text.position.x, 1, text.position.z]}
// class
wrapperClass="distance-text-wrapper"
className="distance-text"
// other
zIndexRange={[1, 0]}
prepend
sprite
>
<div
className={`Reference_Distance line-${text.userData.userData}`}
>
{text.distance} m
</div>
</Html>
)}
</mesh>
</group>
);
};
export default ReferenceDistanceText;

View File

@@ -1,48 +0,0 @@
import * as THREE from 'three';
import { Html } from '@react-three/drei';
import { useState, useEffect } from 'react';
import { useActiveLayer } from '../../../../store/store';
const ReferenceDistanceText = ({ line }: { line: any }) => {
interface TextState {
distance: string;
position: THREE.Vector3;
userData: any;
layer: any;
}
const [text, setTexts] = useState<TextState | null>(null);
const { activeLayer } = useActiveLayer();
useEffect(() => {
if (line) {
if (line.parent === null) {
setTexts(null);
return;
}
const distance = line.userData.linePoints.cursorPosition.distanceTo(line.userData.linePoints.startPoint);
const midpoint = new THREE.Vector3().addVectors(line.userData.linePoints.cursorPosition, line.userData.linePoints.startPoint).divideScalar(2);
const newTexts = {
distance: distance.toFixed(1),
position: midpoint,
userData: line,
layer: activeLayer
};
setTexts(newTexts);
}
});
return (
<group name='Reference_Distance_Text'>
<mesh>
{text !== null &&
< Html transform sprite key={text.distance} userData={text.userData} scale={5} position={[text.position.x, 1, text.position.z]} style={{ pointerEvents: 'none' }}>
<div className={`Reference_Distance line-${text.userData.userData}`}>{text.distance} m</div>
</Html>
}
</mesh>
</group >
);
};
export default ReferenceDistanceText;

View File

@@ -1,5 +1,5 @@
import { useFrame, useThree } from "@react-three/fiber";
import { useAddAction, useDeleteModels, useRoofVisibility, useToggleView, useWallVisibility, useUpdateScene } from "../../../store/store";
import { useAddAction, useDeleteTool, useRoofVisibility, useToggleView, useWallVisibility, useUpdateScene } from "../../../store/store";
import hideRoof from "../geomentries/roofs/hideRoof";
import hideWalls from "../geomentries/walls/hideWalls";
import addAndUpdateReferencePillar from "../geomentries/pillars/addAndUpdateReferencePillar";
@@ -16,7 +16,7 @@ const FloorGroup = ({ floorGroup, lines, referencePole, hoveredDeletablePillar }
const { toggleView, setToggleView } = useToggleView();
const { scene, camera, pointer, raycaster, gl } = useThree();
const { addAction, setAddAction } = useAddAction();
const { deleteModels, setDeleteModels } = useDeleteModels();
const { deleteTool, setDeleteTool } = useDeleteTool();
const { updateScene, setUpdateScene } = useUpdateScene();
useEffect(() => {
@@ -56,7 +56,7 @@ const FloorGroup = ({ floorGroup, lines, referencePole, hoveredDeletablePillar }
if (addAction === "pillar") {
addPillar(referencePole, floorGroup);
}
if (deleteModels) {
if (deleteTool) {
DeletePillar(hoveredDeletablePillar, floorGroup);
}
}
@@ -78,7 +78,7 @@ const FloorGroup = ({ floorGroup, lines, referencePole, hoveredDeletablePillar }
canvasElement.removeEventListener("mouseup", onMouseUp);
canvasElement.removeEventListener("mousemove", onMouseMove);
};
}, [deleteModels, addAction])
}, [deleteTool, addAction])
useFrame(() => {
hideRoof(roofVisibility, floorGroup, camera);
@@ -87,7 +87,7 @@ const FloorGroup = ({ floorGroup, lines, referencePole, hoveredDeletablePillar }
if (addAction === "pillar") {
addAndUpdateReferencePillar(raycaster, floorGroup, referencePole);
}
if (deleteModels) {
if (deleteTool) {
DeletableHoveredPillar(state, floorGroup, hoveredDeletablePillar);
}
})

View File

@@ -1,26 +1,11 @@
import { useFrame, useThree } from "@react-three/fiber";
import {
useActiveTool,
useAsset3dWidget,
useCamMode,
useDeletableFloorItem,
useDeleteModels,
useFloorItems,
useLoadingProgress,
useRenderDistance,
useselectedFloorItem,
useSelectedItem,
useSimulationStates,
useSocketStore,
useToggleView,
useTransformMode,
} from "../../../store/store";
import { useActiveTool, useAsset3dWidget, useCamMode, useDeletableFloorItem, useDeleteTool, useFloorItems, useLoadingProgress, useRenderDistance, useSelectedFloorItem, useSelectedItem, useSimulationStates, useSocketStore, useToggleView, useTransformMode, } from "../../../store/store";
import assetVisibility from "../geomentries/assets/assetVisibility";
import { useEffect } from "react";
import * as THREE from "three";
import * as Types from "../../../types/world/worldTypes";
import assetManager, {
cancelOngoingTasks,
cancelOngoingTasks,
} from "../geomentries/assets/assetManager";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader";
@@ -31,413 +16,315 @@ import addAssetModel from "../geomentries/assets/addAssetModel";
import { getFloorAssets } from "../../../services/factoryBuilder/assest/floorAsset/getFloorItemsApi";
import useModuleStore from "../../../store/useModuleStore";
// import { retrieveGLTF } from "../../../utils/indexDB/idbUtils";
const assetManagerWorker = new Worker(
new URL(
"../../../services/factoryBuilder/webWorkers/assetManagerWorker.js",
import.meta.url
)
);
const gltfLoaderWorker = new Worker(
new URL(
"../../../services/factoryBuilder/webWorkers/gltfLoaderWorker.js",
import.meta.url
)
);
const assetManagerWorker = new Worker(new URL("../../../services/factoryBuilder/webWorkers/assetManagerWorker.js", import.meta.url));
const gltfLoaderWorker = new Worker(new URL("../../../services/factoryBuilder/webWorkers/gltfLoaderWorker.js", import.meta.url));
const FloorItemsGroup = ({
itemsGroup,
hoveredDeletableFloorItem,
AttachedObject,
floorGroup,
tempLoader,
isTempLoader,
plane,
}: any) => {
const state: Types.ThreeState = useThree();
const { raycaster, controls }: any = state;
const { renderDistance } = useRenderDistance();
const { toggleView } = useToggleView();
const { floorItems, setFloorItems } = useFloorItems();
const { camMode } = useCamMode();
const { deleteModels } = useDeleteModels();
const { setDeletableFloorItem } = useDeletableFloorItem();
const { transformMode } = useTransformMode();
const { setselectedFloorItem } = useselectedFloorItem();
const { activeTool } = useActiveTool();
const { selectedItem, setSelectedItem } = useSelectedItem();
const { simulationStates, setSimulationStates } = useSimulationStates();
const { setLoadingProgress } = useLoadingProgress();
const { activeModule } = useModuleStore();
const { socket } = useSocketStore();
const loader = new GLTFLoader();
const dracoLoader = new DRACOLoader();
const FloorItemsGroup = ({ itemsGroup, hoveredDeletableFloorItem, AttachedObject, floorGroup, tempLoader, isTempLoader, plane, }: any) => {
const state: Types.ThreeState = useThree();
const { raycaster, controls }: any = state;
const { renderDistance } = useRenderDistance();
const { toggleView } = useToggleView();
const { floorItems, setFloorItems } = useFloorItems();
const { camMode } = useCamMode();
const { deleteTool } = useDeleteTool();
const { setDeletableFloorItem } = useDeletableFloorItem();
const { transformMode } = useTransformMode();
const { setSelectedFloorItem } = useSelectedFloorItem();
const { activeTool } = useActiveTool();
const { selectedItem, setSelectedItem } = useSelectedItem();
const { simulationStates, setSimulationStates } = useSimulationStates();
const { setLoadingProgress } = useLoadingProgress();
const { activeModule } = useModuleStore();
const { socket } = useSocketStore();
const loader = new GLTFLoader();
const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath(
"https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/libs/draco/gltf/"
);
loader.setDRACOLoader(dracoLoader);
dracoLoader.setDecoderPath("https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/libs/draco/gltf/");
loader.setDRACOLoader(dracoLoader);
useEffect(() => {
const email = localStorage.getItem("email");
const organization = email!.split("@")[1].split(".")[0];
useEffect(() => {
const email = localStorage.getItem("email");
const organization = email!.split("@")[1].split(".")[0];
let totalAssets = 0;
let loadedAssets = 0;
let totalAssets = 0;
let loadedAssets = 0;
const updateLoadingProgress = (progress: number) => {
if (progress < 100) {
setLoadingProgress(progress);
} else if (progress === 100) {
setTimeout(() => {
setLoadingProgress(100);
setTimeout(() => {
setLoadingProgress(0);
}, 1500);
}, 1000);
}
};
const updateLoadingProgress = (progress: number) => {
if (progress < 100) {
setLoadingProgress(progress);
} else if (progress === 100) {
setTimeout(() => {
setLoadingProgress(100);
setTimeout(() => {
setLoadingProgress(0);
}, 1500);
}, 1000);
}
};
getFloorAssets(organization).then((data) => {
if (data.length > 0) {
const uniqueItems = (data as Types.FloorItems).filter(
(item, index, self) =>
index === self.findIndex((t) => t.modelfileID === item.modelfileID)
);
totalAssets = uniqueItems.length;
if (totalAssets === 0) {
updateLoadingProgress(100);
return;
}
gltfLoaderWorker.postMessage({ floorItems: data });
} else {
gltfLoaderWorker.postMessage({ floorItems: [] });
loadInitialFloorItems(itemsGroup, setFloorItems, setSimulationStates);
updateLoadingProgress(100);
}
});
gltfLoaderWorker.onmessage = async (event) => {
if (event.data.message === "gltfLoaded" && event.data.modelBlob) {
const blobUrl = URL.createObjectURL(event.data.modelBlob);
loader.load(blobUrl, (gltf) => {
URL.revokeObjectURL(blobUrl);
THREE.Cache.remove(blobUrl);
THREE.Cache.add(event.data.modelID, gltf);
loadedAssets++;
const progress = Math.round((loadedAssets / totalAssets) * 100);
updateLoadingProgress(progress);
if (loadedAssets === totalAssets) {
loadInitialFloorItems(itemsGroup, setFloorItems, setSimulationStates);
updateLoadingProgress(100);
}
getFloorAssets(organization).then((data) => {
if (data.length > 0) {
const uniqueItems = (data as Types.FloorItems).filter((item, index, self) => index === self.findIndex((t) => t.modelfileID === item.modelfileID));
totalAssets = uniqueItems.length;
if (totalAssets === 0) {
updateLoadingProgress(100);
return;
}
gltfLoaderWorker.postMessage({ floorItems: data });
} else {
gltfLoaderWorker.postMessage({ floorItems: [] });
loadInitialFloorItems(itemsGroup, setFloorItems, setSimulationStates);
updateLoadingProgress(100);
}
});
}
};
}, []);
useEffect(() => {
assetManagerWorker.onmessage = async (event) => {
cancelOngoingTasks(); // Cancel the ongoing process
await assetManager(event.data, itemsGroup, loader);
};
}, [assetManagerWorker]);
gltfLoaderWorker.onmessage = async (event) => {
if (event.data.message === "gltfLoaded" && event.data.modelBlob) {
const blobUrl = URL.createObjectURL(event.data.modelBlob);
useEffect(() => {
if (toggleView) return;
loader.load(blobUrl, (gltf) => {
URL.revokeObjectURL(blobUrl);
THREE.Cache.remove(blobUrl);
THREE.Cache.add(event.data.modelID, gltf);
const uuids: string[] = [];
itemsGroup.current?.children.forEach((child: any) => {
uuids.push(child.uuid);
});
const cameraPosition = state.camera.position;
loadedAssets++;
const progress = Math.round((loadedAssets / totalAssets) * 100);
updateLoadingProgress(progress);
assetManagerWorker.postMessage({
floorItems,
cameraPosition,
uuids,
renderDistance,
});
}, [camMode, renderDistance]);
if (loadedAssets === totalAssets) {
loadInitialFloorItems(itemsGroup, setFloorItems, setSimulationStates);
updateLoadingProgress(100);
}
});
}
};
}, []);
useEffect(() => {
const controls: any = state.controls;
const camera: any = state.camera;
useEffect(() => {
assetManagerWorker.onmessage = async (event) => {
cancelOngoingTasks(); // Cancel the ongoing process
await assetManager(event.data, itemsGroup, loader);
};
}, [assetManagerWorker]);
if (controls) {
let intervalId: NodeJS.Timeout | null = null;
const handleChange = () => {
useEffect(() => {
if (toggleView) return;
const uuids: string[] = [];
itemsGroup.current?.children.forEach((child: any) => {
uuids.push(child.uuid);
});
const cameraPosition = camera.position;
itemsGroup.current?.children.forEach((child: any) => { uuids.push(child.uuid); });
const cameraPosition = state.camera.position;
assetManagerWorker.postMessage({
floorItems,
cameraPosition,
uuids,
renderDistance,
});
};
assetManagerWorker.postMessage({ floorItems, cameraPosition, uuids, renderDistance, });
}, [camMode, renderDistance]);
const startInterval = () => {
if (!intervalId) {
intervalId = setInterval(handleChange, 50);
useEffect(() => {
const controls: any = state.controls;
const camera: any = state.camera;
if (controls) {
let intervalId: NodeJS.Timeout | null = null;
const handleChange = () => {
if (toggleView) return;
const uuids: string[] = [];
itemsGroup.current?.children.forEach((child: any) => { uuids.push(child.uuid); });
const cameraPosition = camera.position;
assetManagerWorker.postMessage({ floorItems, cameraPosition, uuids, renderDistance, });
};
const startInterval = () => {
if (!intervalId) {
intervalId = setInterval(handleChange, 50);
}
};
const stopInterval = () => {
handleChange();
if (intervalId) {
clearInterval(intervalId);
intervalId = null;
}
};
controls.addEventListener("rest", handleChange);
controls.addEventListener("rest", stopInterval);
controls.addEventListener("control", startInterval);
controls.addEventListener("controlend", stopInterval);
return () => {
controls.removeEventListener("rest", handleChange);
controls.removeEventListener("rest", stopInterval);
controls.removeEventListener("control", startInterval);
controls.removeEventListener("controlend", stopInterval);
if (intervalId) {
clearInterval(intervalId);
}
};
}
};
}, [state.controls, floorItems, toggleView, renderDistance]);
const stopInterval = () => {
handleChange();
if (intervalId) {
clearInterval(intervalId);
intervalId = null;
}
};
useEffect(() => {
const canvasElement = state.gl.domElement;
let drag = false;
let isLeftMouseDown = false;
controls.addEventListener("rest", handleChange);
controls.addEventListener("rest", stopInterval);
controls.addEventListener("control", startInterval);
controls.addEventListener("controlend", stopInterval);
return () => {
controls.removeEventListener("rest", handleChange);
controls.removeEventListener("rest", stopInterval);
controls.removeEventListener("control", startInterval);
controls.removeEventListener("controlend", stopInterval);
if (intervalId) {
clearInterval(intervalId);
}
};
}
}, [state.controls, floorItems, toggleView, renderDistance]);
useEffect(() => {
const canvasElement = state.gl.domElement;
let drag = false;
let isLeftMouseDown = false;
const onMouseDown = (evt: any) => {
if (evt.button === 0) {
isLeftMouseDown = true;
drag = false;
}
};
const onMouseMove = () => {
if (isLeftMouseDown) {
drag = true;
}
};
const onMouseUp = async (evt: any) => {
if (controls) {
(controls as any).enabled = true;
}
if (evt.button === 0) {
isLeftMouseDown = false;
if (drag) return;
if (deleteModels) {
DeleteFloorItems(
itemsGroup,
hoveredDeletableFloorItem,
setFloorItems,
setSimulationStates,
socket
);
}
const Mode = transformMode;
if (Mode !== null || activeTool === "cursor") {
if (!itemsGroup.current) return;
let intersects = raycaster.intersectObjects(
itemsGroup.current.children,
true
);
if (
intersects.length > 0 &&
intersects[0]?.object?.parent?.parent?.position &&
intersects[0]?.object?.parent?.parent?.scale &&
intersects[0]?.object?.parent?.parent?.rotation
) {
// let currentObject = intersects[0].object;
// while (currentObject) {
// if (currentObject.name === "Scene") {
// break;
// }
// currentObject = currentObject.parent as THREE.Object3D;
// }
// if (currentObject) {
// AttachedObject.current = currentObject as any;
// setselectedFloorItem(AttachedObject.current!);
// }
} else {
const target = controls.getTarget(new THREE.Vector3());
await controls.setTarget(target.x, 0, target.z, true);
setselectedFloorItem(null);
}
}
}
};
const onDblClick = async (evt: any) => {
if (evt.button === 0) {
isLeftMouseDown = false;
if (drag) return;
const Mode = transformMode;
if (Mode !== null || activeTool === "cursor") {
if (!itemsGroup.current) return;
let intersects = raycaster.intersectObjects(
itemsGroup.current.children,
true
);
if (
intersects.length > 0 &&
intersects[0]?.object?.parent?.parent?.position &&
intersects[0]?.object?.parent?.parent?.scale &&
intersects[0]?.object?.parent?.parent?.rotation
) {
let currentObject = intersects[0].object;
while (currentObject) {
if (currentObject.name === "Scene") {
break;
}
currentObject = currentObject.parent as THREE.Object3D;
const onMouseDown = (evt: any) => {
if (evt.button === 0) {
isLeftMouseDown = true;
drag = false;
}
if (currentObject) {
AttachedObject.current = currentObject as any;
// controls.fitToSphere(AttachedObject.current!, true);
};
const bbox = new THREE.Box3().setFromObject(
AttachedObject.current
);
const size = bbox.getSize(new THREE.Vector3());
const center = bbox.getCenter(new THREE.Vector3());
const front = new THREE.Vector3(0, 0, 1);
AttachedObject.current.localToWorld(front);
front.sub(AttachedObject.current.position).normalize();
const distance = Math.max(size.x, size.y, size.z) * 2;
const newPosition = center
.clone()
.addScaledVector(front, distance);
controls.setPosition(
newPosition.x,
newPosition.y,
newPosition.z,
true
);
controls.setTarget(center.x, center.y, center.z, true);
controls.fitToBox(AttachedObject.current!, true, {
cover: true,
paddingTop: 5,
paddingLeft: 5,
paddingBottom: 5,
paddingRight: 5,
});
setselectedFloorItem(AttachedObject.current!);
const onMouseMove = () => {
if (isLeftMouseDown) {
drag = true;
}
};
const onMouseUp = async (evt: any) => {
if (controls) {
(controls as any).enabled = true;
}
if (evt.button === 0) {
isLeftMouseDown = false;
if (drag) return;
if (deleteTool) {
DeleteFloorItems(itemsGroup, hoveredDeletableFloorItem, setFloorItems, setSimulationStates, socket);
// Remove EventData if there are any in the asset.
}
const Mode = transformMode;
if (Mode !== null || activeTool === "cursor") {
if (!itemsGroup.current) return;
let intersects = raycaster.intersectObjects(
itemsGroup.current.children,
true
);
if (intersects.length > 0 && intersects[0]?.object?.parent?.parent?.position && intersects[0]?.object?.parent?.parent?.scale && intersects[0]?.object?.parent?.parent?.rotation) {
// let currentObject = intersects[0].object;
// while (currentObject) {
// if (currentObject.name === "Scene") {
// break;
// }
// currentObject = currentObject.parent as THREE.Object3D;
// }
// if (currentObject) {
// AttachedObject.current = currentObject as any;
// setSelectedFloorItem(AttachedObject.current!);
// }
} else {
const target = controls.getTarget(new THREE.Vector3());
await controls.setTarget(target.x, 0, target.z, true);
setSelectedFloorItem(null);
}
}
}
};
const onDblClick = async (evt: any) => {
if (evt.button === 0) {
isLeftMouseDown = false;
if (drag) return;
const Mode = transformMode;
if (Mode !== null || activeTool === "cursor") {
if (!itemsGroup.current) return;
let intersects = raycaster.intersectObjects(itemsGroup.current.children, true);
if (intersects.length > 0 && intersects[0]?.object?.parent?.parent?.position && intersects[0]?.object?.parent?.parent?.scale && intersects[0]?.object?.parent?.parent?.rotation) {
let currentObject = intersects[0].object;
while (currentObject) {
if (currentObject.name === "Scene") {
break;
}
currentObject = currentObject.parent as THREE.Object3D;
}
if (currentObject) {
AttachedObject.current = currentObject as any;
// controls.fitToSphere(AttachedObject.current!, true);
const bbox = new THREE.Box3().setFromObject(AttachedObject.current);
const size = bbox.getSize(new THREE.Vector3());
const center = bbox.getCenter(new THREE.Vector3());
const front = new THREE.Vector3(0, 0, 1);
AttachedObject.current.localToWorld(front);
front.sub(AttachedObject.current.position).normalize();
const distance = Math.max(size.x, size.y, size.z) * 2;
const newPosition = center.clone().addScaledVector(front, distance);
controls.setPosition(newPosition.x, newPosition.y, newPosition.z, true);
controls.setTarget(center.x, center.y, center.z, true);
controls.fitToBox(AttachedObject.current!, true, { cover: true, paddingTop: 5, paddingLeft: 5, paddingBottom: 5, paddingRight: 5, });
setSelectedFloorItem(AttachedObject.current!);
}
} else {
const target = controls.getTarget(new THREE.Vector3());
await controls.setTarget(target.x, 0, target.z, true);
setSelectedFloorItem(null);
}
}
}
};
const onDrop = (event: any) => {
if (!event.dataTransfer?.files[0]) return;
if (selectedItem.id !== "" && event.dataTransfer?.files[0]) {
addAssetModel(raycaster, state.camera, state.pointer, floorGroup, setFloorItems, itemsGroup, isTempLoader, tempLoader, socket, selectedItem, setSelectedItem, setSimulationStates, plane);
}
};
const onDragOver = (event: any) => {
event.preventDefault();
};
if (activeModule === "builder") {
canvasElement.addEventListener("mousedown", onMouseDown);
canvasElement.addEventListener("mouseup", onMouseUp);
canvasElement.addEventListener("mousemove", onMouseMove);
canvasElement.addEventListener("dblclick", onDblClick);
canvasElement.addEventListener("drop", onDrop);
canvasElement.addEventListener("dragover", onDragOver);
} else {
if (controls) {
const target = controls.getTarget(new THREE.Vector3());
controls.setTarget(target.x, 0, target.z, true);
setSelectedFloorItem(null);
}
} else {
const target = controls.getTarget(new THREE.Vector3());
await controls.setTarget(target.x, 0, target.z, true);
setselectedFloorItem(null);
}
}
}
};
const onDrop = (event: any) => {
if (!event.dataTransfer?.files[0]) return;
return () => {
canvasElement.removeEventListener("mousedown", onMouseDown);
canvasElement.removeEventListener("mouseup", onMouseUp);
canvasElement.removeEventListener("mousemove", onMouseMove);
canvasElement.removeEventListener("dblclick", onDblClick);
canvasElement.removeEventListener("drop", onDrop);
canvasElement.removeEventListener("dragover", onDragOver);
};
}, [deleteTool, transformMode, controls, selectedItem, state.camera, state.pointer, activeTool, activeModule,]);
if (selectedItem.id !== "" && event.dataTransfer?.files[0]) {
addAssetModel(
raycaster,
state.camera,
state.pointer,
floorGroup,
setFloorItems,
itemsGroup,
isTempLoader,
tempLoader,
socket,
selectedItem,
setSelectedItem,
setSimulationStates,
plane
);
}
};
useFrame(() => {
if (controls)
assetVisibility(itemsGroup, state.camera.position, renderDistance);
if (deleteTool && activeModule === "builder") {
DeletableHoveredFloorItems(state, itemsGroup, hoveredDeletableFloorItem, setDeletableFloorItem);
} else if (!deleteTool) {
if (hoveredDeletableFloorItem.current) {
hoveredDeletableFloorItem.current = undefined;
setDeletableFloorItem(null);
}
}
});
const onDragOver = (event: any) => {
event.preventDefault();
};
if (activeModule === "builder") {
canvasElement.addEventListener("mousedown", onMouseDown);
canvasElement.addEventListener("mouseup", onMouseUp);
canvasElement.addEventListener("mousemove", onMouseMove);
canvasElement.addEventListener("dblclick", onDblClick);
canvasElement.addEventListener("drop", onDrop);
canvasElement.addEventListener("dragover", onDragOver);
} else {
if (controls) {
const target = controls.getTarget(new THREE.Vector3());
controls.setTarget(target.x, 0, target.z, true);
setselectedFloorItem(null);
}
}
return () => {
canvasElement.removeEventListener("mousedown", onMouseDown);
canvasElement.removeEventListener("mouseup", onMouseUp);
canvasElement.removeEventListener("mousemove", onMouseMove);
canvasElement.removeEventListener("dblclick", onDblClick);
canvasElement.removeEventListener("drop", onDrop);
canvasElement.removeEventListener("dragover", onDragOver);
};
}, [
deleteModels,
transformMode,
controls,
selectedItem,
state.camera,
state.pointer,
activeTool,
activeModule,
]);
useFrame(() => {
if (controls)
assetVisibility(itemsGroup, state.camera.position, renderDistance);
if (deleteModels) {
DeletableHoveredFloorItems(
state,
itemsGroup,
hoveredDeletableFloorItem,
setDeletableFloorItem
);
} else if (!deleteModels) {
if (hoveredDeletableFloorItem.current) {
hoveredDeletableFloorItem.current = undefined;
setDeletableFloorItem(null);
}
}
});
return <group ref={itemsGroup} name="itemsGroup"></group>;
return <group ref={itemsGroup} name="itemsGroup"></group>;
};
export default FloorItemsGroup;

View File

@@ -1,5 +1,5 @@
import { useEffect } from "react";
import { useDeleteModels, useDeletePointOrLine, useObjectPosition, useObjectRotation, useObjectScale, useSelectedWallItem, useSocketStore, useWallItems } from "../../../store/store";
import { useDeleteTool, useDeletePointOrLine, useObjectPosition, useObjectRotation, useObjectScale, useSelectedWallItem, useSocketStore, useWallItems } from "../../../store/store";
import { Csg } from "../csg/csg";
import * as Types from "../../../types/world/worldTypes";
import * as CONSTANTS from "../../../types/world/worldConstants";
@@ -9,20 +9,21 @@ import handleMeshMissed from "../eventFunctions/handleMeshMissed";
import DeleteWallItems from "../geomentries/walls/deleteWallItems";
import loadInitialWallItems from "../../scene/IntialLoad/loadInitialWallItems";
import AddWallItems from "../geomentries/walls/addWallItems";
import useModuleStore from "../../../store/useModuleStore";
const WallItemsGroup = ({ currentWallItem, AssetConfigurations, hoveredDeletableWallItem, selectedItemsIndex, setSelectedItemsIndex, CSGGroup }: any) => {
const { deleteModels, setDeleteModels } = useDeleteModels();
const state = useThree();
const { socket } = useSocketStore();
const { pointer, camera, raycaster } = state;
const { deleteTool, setDeleteTool } = useDeleteTool();
const { wallItems, setWallItems } = useWallItems();
const { objectPosition, setObjectPosition } = useObjectPosition();
const { objectScale, setObjectScale } = useObjectScale();
const { objectRotation, setObjectRotation } = useObjectRotation();
const { deletePointOrLine, setDeletePointOrLine } = useDeletePointOrLine();
const { selectedWallItem, setSelectedWallItem } = useSelectedWallItem();
const { socket } = useSocketStore();
const state = useThree();
const { pointer, camera, raycaster } = state;
const { activeModule } = useModuleStore();
useEffect(() => {
// Load Wall Items from the backend
@@ -209,7 +210,7 @@ const WallItemsGroup = ({ currentWallItem, AssetConfigurations, hoveredDeletable
const onMouseUp = (evt: any) => {
if (evt.button === 0) {
isLeftMouseDown = false;
if (!drag && deleteModels) {
if (!drag && deleteTool && activeModule === "builder") {
DeleteWallItems(hoveredDeletableWallItem, setWallItems, wallItems, socket);
}
}
@@ -224,7 +225,7 @@ const WallItemsGroup = ({ currentWallItem, AssetConfigurations, hoveredDeletable
const onDrop = (event: any) => {
if (!event.dataTransfer?.files[0]) return
pointer.x = (event.clientX / window.innerWidth) * 2 - 1;
pointer.y = -(event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
@@ -256,15 +257,15 @@ const WallItemsGroup = ({ currentWallItem, AssetConfigurations, hoveredDeletable
canvasElement.removeEventListener("drop", onDrop);
canvasElement.removeEventListener("dragover", onDragOver);
};
}, [deleteModels, wallItems])
}, [deleteTool, wallItems])
useEffect(() => {
if (deleteModels) {
if (deleteTool && activeModule === "builder") {
handleMeshMissed(currentWallItem, setSelectedWallItem, setSelectedItemsIndex);
setSelectedWallItem(null);
setSelectedItemsIndex(null);
}
}, [deleteModels])
}, [deleteTool])
return (
<>

View File

@@ -1,5 +1,5 @@
import { Geometry } from "@react-three/csg";
import { useDeleteModels, useSelectedWallItem, useToggleView, useTransformMode, useWallItems, useWalls } from "../../../store/store";
import { useDeleteTool, useSelectedWallItem, useToggleView, useTransformMode, useWallItems, useWalls } from "../../../store/store";
import handleMeshDown from "../eventFunctions/handleMeshDown";
import handleMeshMissed from "../eventFunctions/handleMeshMissed";
import WallsMesh from "./wallsMesh";
@@ -11,13 +11,13 @@ const WallsAndWallItems = ({ CSGGroup, AssetConfigurations, setSelectedItemsInde
const { walls, setWalls } = useWalls();
const { wallItems, setWallItems } = useWallItems();
const { toggleView, setToggleView } = useToggleView();
const { deleteModels, setDeleteModels } = useDeleteModels();
const { deleteTool, setDeleteTool } = useDeleteTool();
const { transformMode, setTransformMode } = useTransformMode();
const { selectedWallItem, setSelectedWallItem } = useSelectedWallItem();
useEffect(() => {
if (transformMode === null) {
if (!deleteModels) {
if (!deleteTool) {
handleMeshMissed(currentWallItem, setSelectedWallItem, setSelectedItemsIndex);
setSelectedWallItem(null);
setSelectedItemsIndex(null);
@@ -33,12 +33,12 @@ const WallsAndWallItems = ({ CSGGroup, AssetConfigurations, setSelectedItemsInde
receiveShadow
visible={!toggleView}
onClick={(event) => {
if (!deleteModels && transformMode !== null) {
if (!deleteTool && transformMode !== null) {
handleMeshDown(event, currentWallItem, setSelectedWallItem, setSelectedItemsIndex, wallItems, toggleView);
}
}}
onPointerMissed={() => {
if (!deleteModels) {
if (!deleteTool) {
handleMeshMissed(currentWallItem, setSelectedWallItem, setSelectedItemsIndex);
setSelectedWallItem(null);
setSelectedItemsIndex(null);

File diff suppressed because it is too large Load Diff

View File

@@ -2,7 +2,7 @@ import { useEffect } from "react";
import * as THREE from 'three';
import * as Types from '../../../types/world/worldTypes';
import * as CONSTANTS from "../../../types/world/worldConstants";
import { useActiveLayer, useSocketStore, useDeleteModels, useDeletePointOrLine, useMovePoint, useToggleView, useUpdateScene, useNewLines, useToolMode } from "../../../store/store";
import { useActiveLayer, useSocketStore, useDeleteTool, useDeletePointOrLine, useMovePoint, useToggleView, useUpdateScene, useNewLines, useToolMode } from "../../../store/store";
import { useThree } from "@react-three/fiber";
import arrayLineToObject from "../geomentries/lines/lineConvertions/arrayLineToObject";
import addPointToScene from "../geomentries/points/addPointToScene";
@@ -14,7 +14,7 @@ import loadZones from "../geomentries/zones/loadZones";
const ZoneGroup = ({ zoneGroup, plane, floorPlanGroupLine, floorPlanGroupPoint, line, lines, currentLayerPoint, dragPointControls, floorPlanGroup, ReferenceLineMesh, LineCreated, isSnapped, ispreSnapped, snappedPoint, isSnappedUUID, isAngleSnapped, anglesnappedPoint }: any) => {
const { toggleView, setToggleView } = useToggleView();
const { deleteModels, setDeleteModels } = useDeleteModels();
const { deleteTool, setDeleteTool } = useDeleteTool();
const { deletePointOrLine, setDeletePointOrLine } = useDeletePointOrLine();
const { toolMode, setToolMode } = useToolMode();
const { movePoint, setMovePoint } = useMovePoint();
@@ -35,7 +35,7 @@ const ZoneGroup = ({ zoneGroup, plane, floorPlanGroupLine, floorPlanGroupPoint,
if (toolMode === "Zone") {
setDeletePointOrLine(false);
setMovePoint(false);
setDeleteModels(false);
setDeleteTool(false);
} else {
removeSoloPoint(line, floorPlanGroupLine, floorPlanGroupPoint);
removeReferenceLine(floorPlanGroup, ReferenceLineMesh, LineCreated, line);

View File

@@ -185,10 +185,9 @@ const CamModelsGroup = () => {
position={[-0.015, 0, 0.7]}
>
<CollabUserIcon
userImage={""}
userImage={cam.userData.userImage ||""}
userName={cam.userData.userName}
index={index}
color={getAvatarColor(index)}
color={getAvatarColor(index, cam.userData.userName)}
/>
</Html>
</primitive>

View File

@@ -4,14 +4,12 @@ import CustomAvatar from "./users/Avatar";
interface CollabUserIconProps {
userName: string;
userImage?: string;
index?: number;
color: string;
}
const CollabUserIcon: React.FC<CollabUserIconProps> = ({
userImage,
userName,
index = 0,
color,
}) => {
return (
@@ -20,24 +18,7 @@ const CollabUserIcon: React.FC<CollabUserIconProps> = ({
{userImage ? (
<img className="user-image" src={userImage} alt={userName} />
) : (
<CustomAvatar name={userName} index={index} color={color} />
// <div
// className="user-image"
// style={{
// lineHeight: "30px",
// textTransform: "uppercase",
// textAlign: "center",
// fontSize: "16px",
// borderRadius: "50%",
// backgroundColor: color,
// overflow: "hidden",
// backgroundSize: "cover",
// backgroundPosition: "center",
// color: "white",
// fontWeight: "bold",
// }}>
// {userName[0]}
// </div>
<CustomAvatar name={userName} color={color} />
)}
</div>
<div className="user-name" style={{ backgroundColor: color }}>

View File

@@ -105,7 +105,7 @@ export default function SocketResponses({
// console.log(`Getting ${data.data.modelname} from cache`);
const model = cachedModel.scene.clone();
model.uuid = data.data.modeluuid;
model.userData = { name: data.data.modelname, modelId: data.data.modelFileID, modeluuid: data.data.modeluuid };
model.userData = { name: data.data.modelname, modelId: data.data.modelfileID, modeluuid: data.data.modeluuid };
model.position.set(...data.data.position as [number, number, number]);
model.rotation.set(data.data.rotation.x, data.data.rotation.y, data.data.rotation.z);
model.scale.set(...CONSTANTS.assetConfig.defaultScaleBeforeGsap);
@@ -159,7 +159,7 @@ export default function SocketResponses({
url = URL.createObjectURL(indexedDBModel);
} else {
// console.log(`Getting ${data.data.modelname} from Backend`);
url = `${url_Backend_dwinzo}/api/v1/AssetFile/${data.data.modelfileID}`;
url = `${url_Backend_dwinzo}/api/v2/AssetFile/${data.data.modelfileID}`;
const modelBlob = await fetch(url).then((res) => res.blob());
await storeGLTF(data.data.modelfileID, modelBlob);
}
@@ -179,7 +179,7 @@ export default function SocketResponses({
THREE.Cache.remove(url);
const model = gltf.scene;
model.uuid = data.data.modeluuid;
model.userData = { name: data.data.modelname, modelId: data.data.modelFileID, modeluuid: data.data.modeluuid };
model.userData = { name: data.data.modelname, modelId: data.data.modelfileID, modeluuid: data.data.modeluuid };
model.position.set(...data.data.position as [number, number, number]);
model.rotation.set(data.data.rotation.x, data.data.rotation.y, data.data.rotation.z);
model.scale.set(...CONSTANTS.assetConfig.defaultScaleBeforeGsap);

View File

@@ -5,7 +5,6 @@ import { getAvatarColor } from "./functions/getAvatarColor";
interface AvatarProps {
name: string; // Name can be a full name or initials
size?: number;
index?: number;
textColor?: string;
color?: string; // Optional color prop for future use
}
@@ -13,7 +12,6 @@ interface AvatarProps {
const CustomAvatar: React.FC<AvatarProps> = ({
name,
size = 100,
index = 0,
textColor = "#ffffff",
color, // Optional color prop for future use
}) => {
@@ -28,7 +26,7 @@ const CustomAvatar: React.FC<AvatarProps> = ({
const initials = getInitials(name); // Convert name to initials if needed
// Draw background
ctx.fillStyle = color || getAvatarColor(index); // Use color prop or generate color based on index
ctx.fillStyle = color || "#323232"; // Use color prop or generate color based on index
ctx.fillRect(0, 0, size, size);
// Draw initials
@@ -42,7 +40,7 @@ const CustomAvatar: React.FC<AvatarProps> = ({
const dataURL = canvas.toDataURL("image/png");
setImageSrc(dataURL);
}
}, [name, size, textColor, index]);
}, [name, size, textColor]);
if (!imageSrc) {
return null; // Return null while the image is being generated
@@ -55,18 +53,6 @@ const CustomAvatar: React.FC<AvatarProps> = ({
alt="User Avatar"
style={{ width: "100%", height: "100%" }}
/>
// <div
// className="user-image"
// style={{
// width: size,
// height: size,
// borderRadius: "50%",
// overflow: "hidden",
// backgroundSize: "cover",
// backgroundPosition: "center",
// }}>
// {name[0]}
// </div>
);
};

View File

@@ -1,26 +1,67 @@
const avatarColors: string[] = [
"#FF5733", // Red Orange
"#FF5733", // Vivid Orange
"#48ac2a", // Leaf Green
"#0050eb", // Royal Blue
"#0050eb", // Bright Blue
"#FF33A1", // Hot Pink
"#FF8C33", // Deep Orange
"#8C33FF", // Violet
"#FF3333", // Bright Red
"#FF8C33", // Sunset Orange
"#8C33FF", // Violet Purple
"#FF3333", // Fiery Red
"#43c06d", // Emerald Green
"#A133FF", // Amethyst Purple
"#C70039", // Crimson
"#900C3F", // Maroon
"#581845", // Plum
"#3498DB", // Sky Blue
"#2ECC71", // Green Mint
"#E74C3C", // Tomato Red
"#00adff", // Azure
"#DBAD05", // Amber Yellow
"#FF5733", // Red Orange
"#FF33A1", // Hot Pink
"#900C3F", // Maroon
"#A133FF", // Royal Purple
"#C70039", // Crimson Red
"#900C3F", // Deep Burgundy
"#581845", // Plum Purple
"#3859AD", // Steel Blue
"#08873E", // Forest Green
"#E74C3C", // Cherry Red
"#00adff", // Sky Blue
"#DBAD05", // Golden Yellow
"#A13E31", // Brick Red
"#94C40E", // Lime Green
"#060C47", // Midnight Blue
"#2FAFAF", // Teal
];
export function getAvatarColor(index: number): string {
export function getAvatarColor(index: number, name?: string): string {
// Check if the color is already stored in localStorage
const localStorageKey = "userAvatarColors";
// Helper function to check if local storage is available
function isLocalStorageAvailable(): boolean {
try {
const testKey = "__test__";
localStorage.setItem(testKey, "test");
localStorage.removeItem(testKey);
return true;
} catch (e) {
return false;
}
}
// Check if local storage is available
if (isLocalStorageAvailable() && name) {
let userColors = JSON.parse(localStorage.getItem(localStorageKey) || "{}");
// Check if the user already has an assigned color
if (userColors[name]) {
return userColors[name];
}
// Find a new color not already assigned
const usedColors = Object.values(userColors);
const availableColors = avatarColors.filter(color => !usedColors.includes(color));
// Assign a new color
const assignedColor = availableColors.length > 0
? availableColors[0]
: avatarColors[index % avatarColors.length];
userColors[name] = assignedColor;
// Save back to local storage
localStorage.setItem(localStorageKey, JSON.stringify(userColors));
return assignedColor;
}
// Fallback: Assign a color using the index if no name or local storage is unavailable
return avatarColors[index % avatarColors.length];
}

View File

@@ -12,7 +12,7 @@ import { getFloorAssets } from '../../../services/factoryBuilder/assest/floorAss
async function loadInitialFloorItems(
itemsGroup: Types.RefGroup,
setFloorItems: Types.setFloorItemSetState,
setSimulationStates: (paths: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema)[]) => void
setSimulationStates: (paths: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | Types.ArmBotEventsSchema)[]) => void
): Promise<void> {
if (!itemsGroup.current) return;
let url_Backend_dwinzo = `http://${process.env.REACT_APP_SERVER_MARKETPLACE_URL}`;
@@ -83,16 +83,14 @@ async function loadInitialFloorItems(
if (indexedDBModel) {
// console.log(`[IndexedDB] Fetching ${item.modelname}`);
const blobUrl = URL.createObjectURL(indexedDBModel);
loader.load(
blobUrl,
(gltf) => {
URL.revokeObjectURL(blobUrl);
THREE.Cache.remove(blobUrl);
THREE.Cache.add(item.modelfileID!, gltf);
processLoadedModel(gltf.scene.clone(), item, itemsGroup, setFloorItems, setSimulationStates);
modelsLoaded++;
checkLoadingCompletion(modelsLoaded, modelsToLoad, dracoLoader, resolve);
},
loader.load(blobUrl, (gltf) => {
URL.revokeObjectURL(blobUrl);
THREE.Cache.remove(blobUrl);
THREE.Cache.add(item.modelfileID!, gltf);
processLoadedModel(gltf.scene.clone(), item, itemsGroup, setFloorItems, setSimulationStates);
modelsLoaded++;
checkLoadingCompletion(modelsLoaded, modelsToLoad, dracoLoader, resolve);
},
undefined,
(error) => {
toast.error(`[IndexedDB] Error loading ${item.modelname}:`);
@@ -105,17 +103,15 @@ async function loadInitialFloorItems(
// Fetch from Backend
// console.log(`[Backend] Fetching ${item.modelname}`);
const modelUrl = `${url_Backend_dwinzo}/api/v1/AssetFile/${item.modelfileID!}`;
loader.load(
modelUrl,
async (gltf) => {
const modelBlob = await fetch(modelUrl).then((res) => res.blob());
await storeGLTF(item.modelfileID!, modelBlob);
THREE.Cache.add(item.modelfileID!, gltf);
processLoadedModel(gltf.scene.clone(), item, itemsGroup, setFloorItems, setSimulationStates);
modelsLoaded++;
checkLoadingCompletion(modelsLoaded, modelsToLoad, dracoLoader, resolve);
},
const modelUrl = `${url_Backend_dwinzo}/api/v2/AssetFile/${item.modelfileID!}`;
loader.load(modelUrl, async (gltf) => {
const modelBlob = await fetch(modelUrl).then((res) => res.blob());
await storeGLTF(item.modelfileID!, modelBlob);
THREE.Cache.add(item.modelfileID!, gltf);
processLoadedModel(gltf.scene.clone(), item, itemsGroup, setFloorItems, setSimulationStates);
modelsLoaded++;
checkLoadingCompletion(modelsLoaded, modelsToLoad, dracoLoader, resolve);
},
undefined,
(error) => {
toast.error(`[Backend] Error loading ${item.modelname}:`);
@@ -138,7 +134,7 @@ async function loadInitialFloorItems(
},
]);
if (item.eventData || item.modelfileID === '67e3db95c2e8f37134526fb2') {
if (item.eventData) {
processEventData(item, setSimulationStates);
}
@@ -158,7 +154,7 @@ function processLoadedModel(
item: Types.EventData,
itemsGroup: Types.RefGroup,
setFloorItems: Types.setFloorItemSetState,
setSimulationStates: (paths: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema)[]) => void
setSimulationStates: (paths: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | Types.ArmBotEventsSchema)[]) => void
) {
const model = gltf;
model.uuid = item.modeluuid;
@@ -193,7 +189,7 @@ function processLoadedModel(
},
]);
if (item.eventData || item.modelfileID === '67e3db95c2e8f37134526fb2') {
if (item.eventData) {
processEventData(item, setSimulationStates);
}
@@ -211,7 +207,7 @@ function processEventData(item: Types.EventData, setSimulationStates: any) {
data.position = item.position;
data.rotation = [item.rotation.x, item.rotation.y, item.rotation.z];
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema)[]) => [
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | Types.ArmBotEventsSchema)[]) => [
...(prevEvents || []),
data as Types.ConveyorEventsSchema
]);
@@ -222,35 +218,39 @@ function processEventData(item: Types.EventData, setSimulationStates: any) {
data.modeluuid = item.modeluuid;
data.modelName = item.modelname;
data.position = item.position;
data.rotation = [item.rotation.x, item.rotation.y, item.rotation.z];
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema)[]) => [
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | Types.ArmBotEventsSchema)[]) => [
...(prevEvents || []),
data as Types.VehicleEventsSchema
]);
} else if (item.modelfileID === '67e3db95c2e8f37134526fb2') {
} else if (item.eventData?.type === 'StaticMachine') {
const pointUUID = THREE.MathUtils.generateUUID();
const pointPosition = new THREE.Vector3(0, 1.75, 0);
const data: any = item.eventData;
data.modeluuid = item.modeluuid;
data.modelName = item.modelname;
data.position = item.position;
data.rotation = [item.rotation.x, item.rotation.y, item.rotation.z];
const staticMachine: Types.StaticMachineEventsSchema = {
modeluuid: item.modeluuid,
modelName: item.modelname,
type: "StaticMachine",
points: {
uuid: pointUUID,
position: [pointPosition.x, pointPosition.y, pointPosition.z],
actions: { uuid: THREE.MathUtils.generateUUID(), name: 'Action 1', buffer: 'Inherit', material: 'Inherit', isUsed: false },
triggers: { uuid: THREE.MathUtils.generateUUID(), name: 'Trigger 1', type: 'OnComplete' },
connections: { source: { modelUUID: item.modeluuid, pointUUID: pointUUID }, targets: [] },
},
position: item.position
};
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema)[]) => [
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | Types.ArmBotEventsSchema)[]) => [
...(prevEvents || []),
staticMachine as Types.StaticMachineEventsSchema
data as Types.StaticMachineEventsSchema
]);
} else if (item.eventData?.type === 'ArmBot') {
const data: any = item.eventData;
data.modeluuid = item.modeluuid;
data.modelName = item.modelname;
data.position = item.position;
data.rotation = [item.rotation.x, item.rotation.y, item.rotation.z];
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | Types.ArmBotEventsSchema)[]) => [
...(prevEvents || []),
data as Types.ArmBotEventsSchema
]);
}
}

View File

@@ -151,7 +151,7 @@ const CopyPasteControls = ({ itemsGroupRef, copiedObjects, setCopiedObjects, pas
return updatedItems;
});
let eventData: Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | undefined = simulationStates.find((events) => events.modeluuid === obj.userData.modeluuid);
let eventData: Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | Types.ArmBotEventsSchema | undefined = simulationStates.find((events) => events.modeluuid === obj.userData.modeluuid);
const email = localStorage.getItem("email");
const organization = email ? email.split("@")[1].split(".")[0] : "default";
@@ -181,7 +181,10 @@ const CopyPasteControls = ({ itemsGroupRef, copiedObjects, setCopiedObjects, pas
uuid: THREE.MathUtils.generateUUID()
}))
: [defaultAction],
triggers: (eventData as Types.ConveyorEventsSchema)?.points[index].triggers,
triggers: (eventData as Types.ConveyorEventsSchema)?.points[index].triggers.map(trigger => ({
...trigger,
uuid: THREE.MathUtils.generateUUID()
})),
connections: {
source: { modelUUID: obj.uuid, pointUUID },
targets: []
@@ -234,7 +237,7 @@ const CopyPasteControls = ({ itemsGroupRef, copiedObjects, setCopiedObjects, pas
newEventData.position = newFloorItem.position;
newEventData.rotation = [obj.rotation.x, obj.rotation.y, obj.rotation.z];
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema)[]) => [
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | Types.ArmBotEventsSchema)[]) => [
...(prevEvents || []),
newEventData as Types.ConveyorEventsSchema
]);
@@ -260,6 +263,7 @@ const CopyPasteControls = ({ itemsGroupRef, copiedObjects, setCopiedObjects, pas
return {
uuid: pointUUID,
position: vehiclePoint?.position,
// rotation: vehiclePoint?.rotation,
actions: hasActions
? {
...vehiclePoint.actions,
@@ -312,14 +316,206 @@ const CopyPasteControls = ({ itemsGroupRef, copiedObjects, setCopiedObjects, pas
newEventData.modeluuid = newFloorItem.modeluuid;
newEventData.modelName = newFloorItem.modelname;
newEventData.position = newFloorItem.position;
newEventData.rotation = [obj.rotation.x, obj.rotation.y, obj.rotation.z];
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema)[]) => [
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | Types.ArmBotEventsSchema)[]) => [
...(prevEvents || []),
newEventData as Types.VehicleEventsSchema
]);
socket.emit("v2:model-asset:add", data);
} else if (eventData.type === 'StaticMachine' && eventData) {
const createStaticMachinePoint = () => {
const pointUUID = THREE.MathUtils.generateUUID();
const vehiclePoint = (eventData as Types.StaticMachineEventsSchema)?.points;
const hasActions = vehiclePoint?.actions !== undefined;
const defaultAction = {
uuid: THREE.MathUtils.generateUUID(),
name: 'Action 1',
buffer: 0,
material: 'Inherit',
};
return {
uuid: pointUUID,
position: vehiclePoint?.position,
// rotation: vehiclePoint?.rotation,
actions: hasActions
? {
...vehiclePoint.actions,
uuid: THREE.MathUtils.generateUUID()
}
: defaultAction,
triggers: { uuid: THREE.MathUtils.generateUUID(), name: 'Trigger 1', type: 'OnComplete' },
connections: {
source: { modelUUID: obj.uuid, pointUUID },
targets: []
}
};
};
const backendEventData = {
type: 'StaticMachine',
points: createStaticMachinePoint()
};
// API
// setFloorItemApi(
// organization,
// obj.uuid,
// obj.userData.name,
// obj.userData.modelId,
// [worldPosition.x, worldPosition.y, worldPosition.z],
// { "x": obj.rotation.x, "y": obj.rotation.y, "z": obj.rotation.z },
// false,
// true,
// { type: backendEventData.type, points: backendEventData.points }
// );
// SOCKET
const data = {
organization,
modeluuid: newFloorItem.modeluuid,
modelname: newFloorItem.modelname,
modelfileID: newFloorItem.modelfileID,
position: newFloorItem.position,
rotation: { x: obj.rotation.x, y: obj.rotation.y, z: obj.rotation.z },
isLocked: false,
isVisible: true,
eventData: { type: backendEventData.type, points: backendEventData.points },
socketId: socket.id,
};
const newEventData: any = { type: backendEventData.type, points: backendEventData.points };
newEventData.modeluuid = newFloorItem.modeluuid;
newEventData.modelName = newFloorItem.modelname;
newEventData.position = newFloorItem.position;
newEventData.rotation = [obj.rotation.x, obj.rotation.y, obj.rotation.z];
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | Types.ArmBotEventsSchema)[]) => [
...(prevEvents || []),
newEventData as Types.StaticMachineEventsSchema
]);
socket.emit("v2:model-asset:add", data);
} else if (eventData.type === 'ArmBot' && eventData) {
const createArmBotPoint = () => {
const pointUUID = THREE.MathUtils.generateUUID();
const vehiclePoint = (eventData as Types.ArmBotEventsSchema)?.points;
const hasActions = vehiclePoint?.actions !== undefined;
const defaultAction = {
uuid: THREE.MathUtils.generateUUID(),
name: 'Action 1',
buffer: 0,
material: 'Inherit',
};
return {
uuid: pointUUID,
position: vehiclePoint?.position,
// rotation: vehiclePoint?.rotation,
actions: hasActions
? {
...vehiclePoint.actions,
uuid: THREE.MathUtils.generateUUID()
}
: defaultAction,
triggers: {
uuid: THREE.MathUtils.generateUUID(),
name: vehiclePoint.triggers.name,
type: vehiclePoint.triggers.type,
},
connections: {
source: { modelUUID: obj.uuid, pointUUID },
targets: []
}
};
};
const backendEventData = {
type: 'ArmBot',
points: createArmBotPoint()
};
// API
// setFloorItemApi(
// organization,
// obj.uuid,
// obj.userData.name,
// obj.userData.modelId,
// [worldPosition.x, worldPosition.y, worldPosition.z],
// { "x": obj.rotation.x, "y": obj.rotation.y, "z": obj.rotation.z },
// false,
// true,
// { type: backendEventData.type, points: backendEventData.points }
// );
// SOCKET
const data = {
organization,
modeluuid: newFloorItem.modeluuid,
modelname: newFloorItem.modelname,
modelfileID: newFloorItem.modelfileID,
position: newFloorItem.position,
rotation: { x: obj.rotation.x, y: obj.rotation.y, z: obj.rotation.z },
isLocked: false,
isVisible: true,
eventData: { type: backendEventData.type, points: backendEventData.points },
socketId: socket.id,
};
const newEventData: any = { type: backendEventData.type, points: backendEventData.points };
newEventData.modeluuid = newFloorItem.modeluuid;
newEventData.modelName = newFloorItem.modelname;
newEventData.position = newFloorItem.position;
newEventData.rotation = [obj.rotation.x, obj.rotation.y, obj.rotation.z];
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | Types.ArmBotEventsSchema)[]) => [
...(prevEvents || []),
newEventData as Types.ArmBotEventsSchema
]);
socket.emit("v2:model-asset:add", data);
} else {
//REST
// await setFloorItemApi(
// organization,
// obj.uuid,
// obj.userData.name,
// [worldPosition.x, worldPosition.y, worldPosition.z],
// { "x": obj.rotation.x, "y": obj.rotation.y, "z": obj.rotation.z },
// obj.userData.modelId,
// false,
// true,
// );
//SOCKET
const data = {
organization,
modeluuid: newFloorItem.modeluuid,
modelname: newFloorItem.modelname,
modelfileID: newFloorItem.modelfileID,
position: newFloorItem.position,
rotation: { x: obj.rotation.x, y: obj.rotation.y, z: obj.rotation.z },
isLocked: false,
isVisible: true,
socketId: socket.id,
};
socket.emit("v2:model-asset:add", data);
}
} else {

View File

@@ -132,7 +132,7 @@ const DuplicationControls = ({ itemsGroupRef, duplicatedObjects, setDuplicatedOb
return updatedItems;
});
let eventData: Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | undefined = simulationStates.find((events) => events.modeluuid === obj.userData.modeluuid);
let eventData: Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | Types.ArmBotEventsSchema | undefined = simulationStates.find((events) => events.modeluuid === obj.userData.modeluuid);
const email = localStorage.getItem("email");
const organization = email ? email.split("@")[1].split(".")[0] : "default";
@@ -163,7 +163,10 @@ const DuplicationControls = ({ itemsGroupRef, duplicatedObjects, setDuplicatedOb
uuid: THREE.MathUtils.generateUUID()
}))
: [defaultAction],
triggers: (eventData as Types.ConveyorEventsSchema)?.points[index].triggers,
triggers: (eventData as Types.ConveyorEventsSchema)?.points[index].triggers.map(trigger => ({
...trigger,
uuid: THREE.MathUtils.generateUUID()
})),
connections: {
source: { modelUUID: newFloorItem.modeluuid, pointUUID },
targets: []
@@ -174,9 +177,9 @@ const DuplicationControls = ({ itemsGroupRef, duplicatedObjects, setDuplicatedOb
const backendEventData = {
type: 'Conveyor',
points: [
createConveyorPoint(0), // point1
createConveyorPoint(1), // middlePoint
createConveyorPoint(2) // point2
createConveyorPoint(0),
createConveyorPoint(1),
createConveyorPoint(2)
],
speed: (eventData as Types.ConveyorEventsSchema)?.speed
};
@@ -216,7 +219,7 @@ const DuplicationControls = ({ itemsGroupRef, duplicatedObjects, setDuplicatedOb
newEventData.position = newFloorItem.position;
newEventData.rotation = [obj.rotation.x, obj.rotation.y, obj.rotation.z];
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema)[]) => [
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | Types.ArmBotEventsSchema)[]) => [
...(prevEvents || []),
newEventData as Types.ConveyorEventsSchema
]);
@@ -242,6 +245,7 @@ const DuplicationControls = ({ itemsGroupRef, duplicatedObjects, setDuplicatedOb
return {
uuid: pointUUID,
position: vehiclePoint?.position,
// rotation: vehiclePoint?.rotation,
actions: hasActions
? {
...vehiclePoint.actions,
@@ -294,14 +298,206 @@ const DuplicationControls = ({ itemsGroupRef, duplicatedObjects, setDuplicatedOb
newEventData.modeluuid = newFloorItem.modeluuid;
newEventData.modelName = newFloorItem.modelname;
newEventData.position = newFloorItem.position;
newEventData.rotation = [obj.rotation.x, obj.rotation.y, obj.rotation.z];
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema)[]) => [
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | Types.ArmBotEventsSchema)[]) => [
...(prevEvents || []),
newEventData as Types.VehicleEventsSchema
]);
socket.emit("v2:model-asset:add", data);
} else if (eventData.type === 'StaticMachine' && eventData) {
const createStaticMachinePoint = () => {
const pointUUID = THREE.MathUtils.generateUUID();
const vehiclePoint = (eventData as Types.StaticMachineEventsSchema)?.points;
const hasActions = vehiclePoint?.actions !== undefined;
const defaultAction = {
uuid: THREE.MathUtils.generateUUID(),
name: 'Action 1',
buffer: 0,
material: 'Inherit',
};
return {
uuid: pointUUID,
position: vehiclePoint?.position,
// rotation: vehiclePoint?.rotation,
actions: hasActions
? {
...vehiclePoint.actions,
uuid: THREE.MathUtils.generateUUID()
}
: defaultAction,
triggers: { uuid: THREE.MathUtils.generateUUID(), name: 'Trigger 1', type: 'OnComplete' },
connections: {
source: { modelUUID: obj.uuid, pointUUID },
targets: []
}
};
};
const backendEventData = {
type: 'StaticMachine',
points: createStaticMachinePoint()
};
// API
// setFloorItemApi(
// organization,
// obj.uuid,
// obj.userData.name,
// obj.userData.modelId,
// [worldPosition.x, worldPosition.y, worldPosition.z],
// { "x": obj.rotation.x, "y": obj.rotation.y, "z": obj.rotation.z },
// false,
// true,
// { type: backendEventData.type, points: backendEventData.points }
// );
// SOCKET
const data = {
organization,
modeluuid: newFloorItem.modeluuid,
modelname: newFloorItem.modelname,
modelfileID: newFloorItem.modelfileID,
position: newFloorItem.position,
rotation: { x: obj.rotation.x, y: obj.rotation.y, z: obj.rotation.z },
isLocked: false,
isVisible: true,
eventData: { type: backendEventData.type, points: backendEventData.points },
socketId: socket.id,
};
const newEventData: any = { type: backendEventData.type, points: backendEventData.points };
newEventData.modeluuid = newFloorItem.modeluuid;
newEventData.modelName = newFloorItem.modelname;
newEventData.position = newFloorItem.position;
newEventData.rotation = [obj.rotation.x, obj.rotation.y, obj.rotation.z];
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | Types.ArmBotEventsSchema)[]) => [
...(prevEvents || []),
newEventData as Types.StaticMachineEventsSchema
]);
socket.emit("v2:model-asset:add", data);
} else if (eventData.type === 'ArmBot' && eventData) {
const createArmBotPoint = () => {
const pointUUID = THREE.MathUtils.generateUUID();
const vehiclePoint = (eventData as Types.ArmBotEventsSchema)?.points;
const hasActions = vehiclePoint?.actions !== undefined;
const defaultAction = {
uuid: THREE.MathUtils.generateUUID(),
name: 'Action 1',
buffer: 0,
material: 'Inherit',
};
return {
uuid: pointUUID,
position: vehiclePoint?.position,
// rotation: vehiclePoint?.rotation,
actions: hasActions
? {
...vehiclePoint.actions,
uuid: THREE.MathUtils.generateUUID()
}
: defaultAction,
triggers: {
uuid: THREE.MathUtils.generateUUID(),
name: vehiclePoint.triggers.name,
type: vehiclePoint.triggers.type,
},
connections: {
source: { modelUUID: obj.uuid, pointUUID },
targets: []
}
};
};
const backendEventData = {
type: 'ArmBot',
points: createArmBotPoint()
};
// API
// setFloorItemApi(
// organization,
// obj.uuid,
// obj.userData.name,
// obj.userData.modelId,
// [worldPosition.x, worldPosition.y, worldPosition.z],
// { "x": obj.rotation.x, "y": obj.rotation.y, "z": obj.rotation.z },
// false,
// true,
// { type: backendEventData.type, points: backendEventData.points }
// );
// SOCKET
const data = {
organization,
modeluuid: newFloorItem.modeluuid,
modelname: newFloorItem.modelname,
modelfileID: newFloorItem.modelfileID,
position: newFloorItem.position,
rotation: { x: obj.rotation.x, y: obj.rotation.y, z: obj.rotation.z },
isLocked: false,
isVisible: true,
eventData: { type: backendEventData.type, points: backendEventData.points },
socketId: socket.id,
};
const newEventData: any = { type: backendEventData.type, points: backendEventData.points };
newEventData.modeluuid = newFloorItem.modeluuid;
newEventData.modelName = newFloorItem.modelname;
newEventData.position = newFloorItem.position;
newEventData.rotation = [obj.rotation.x, obj.rotation.y, obj.rotation.z];
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | Types.ArmBotEventsSchema)[]) => [
...(prevEvents || []),
newEventData as Types.ArmBotEventsSchema
]);
socket.emit("v2:model-asset:add", data);
} else {
//REST
// await setFloorItemApi(
// organization,
// obj.uuid,
// obj.userData.name,
// [worldPosition.x, worldPosition.y, worldPosition.z],
// { "x": obj.rotation.x, "y": obj.rotation.y, "z": obj.rotation.z },
// obj.userData.modelId,
// false,
// true,
// );
//SOCKET
const data = {
organization,
modeluuid: newFloorItem.modeluuid,
modelname: newFloorItem.modelname,
modelfileID: newFloorItem.modelfileID,
position: newFloorItem.position,
rotation: { x: obj.rotation.x, y: obj.rotation.y, z: obj.rotation.z },
isLocked: false,
isVisible: true,
socketId: socket.id,
};
socket.emit("v2:model-asset:add", data);
}
} else {

View File

@@ -180,12 +180,12 @@ function MoveControls({ movedObjects, setMovedObjects, itemsGroupRef, copiedObje
return updatedItems;
});
let eventData: Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | undefined = simulationStates.find((events) => events.modeluuid === obj.userData.modeluuid);
let eventData: Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | Types.ArmBotEventsSchema | undefined = simulationStates.find((events) => events.modeluuid === obj.userData.modeluuid);
const email = localStorage.getItem("email");
const organization = email ? email.split("@")[1].split(".")[0] : "default";
if (eventData && eventData.type !== 'StaticMachine') {
if (eventData) {
if (eventData.type === 'Conveyor' && eventData) {
const backendEventData = {
@@ -229,7 +229,7 @@ function MoveControls({ movedObjects, setMovedObjects, itemsGroupRef, copiedObje
newEventData.position = newFloorItem.position;
newEventData.rotation = [obj.rotation.x, obj.rotation.y, obj.rotation.z];
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema)[]) => {
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | Types.ArmBotEventsSchema)[]) => {
const updatedEvents = (prevEvents || []).map(event =>
event.modeluuid === newFloorItem.modeluuid
? { ...event, ...newEventData }
@@ -279,8 +279,115 @@ function MoveControls({ movedObjects, setMovedObjects, itemsGroupRef, copiedObje
newEventData.modeluuid = newFloorItem.modeluuid;
newEventData.modelName = newFloorItem.modelname;
newEventData.position = newFloorItem.position;
newEventData.rotation = [obj.rotation.x, obj.rotation.y, obj.rotation.z];
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema)[]) => {
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | Types.ArmBotEventsSchema)[]) => {
const updatedEvents = (prevEvents || []).map(event =>
event.modeluuid === newFloorItem.modeluuid
? { ...event, ...newEventData }
: event
);
return updatedEvents;
});
socket.emit("v2:model-asset:add", data);
} else if (eventData.type === 'StaticMachine' && eventData) {
const backendEventData = {
type: 'StaticMachine',
points: eventData.points,
};
// REST
// await setFloorItemApi(
// organization,
// obj.uuid,
// obj.userData.name,
// obj.userData.modelId,
// [worldPosition.x, worldPosition.y, worldPosition.z],
// { "x": obj.rotation.x, "y": obj.rotation.y, "z": obj.rotation.z },
// false,
// true,
// { type: backendEventData.type, points: backendEventData.points }
// );
//SOCKET
const data = {
organization,
modeluuid: newFloorItem.modeluuid,
modelname: newFloorItem.modelname,
modelfileID: newFloorItem.modelfileID,
position: newFloorItem.position,
rotation: { x: obj.rotation.x, y: obj.rotation.y, z: obj.rotation.z },
isLocked: false,
isVisible: true,
eventData: { type: backendEventData.type, points: backendEventData.points },
socketId: socket.id,
};
const newEventData: any = { type: backendEventData.type, points: backendEventData.points };
newEventData.modeluuid = newFloorItem.modeluuid;
newEventData.modelName = newFloorItem.modelname;
newEventData.position = newFloorItem.position;
newEventData.rotation = [obj.rotation.x, obj.rotation.y, obj.rotation.z];
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | Types.ArmBotEventsSchema)[]) => {
const updatedEvents = (prevEvents || []).map(event =>
event.modeluuid === newFloorItem.modeluuid
? { ...event, ...newEventData }
: event
);
return updatedEvents;
});
socket.emit("v2:model-asset:add", data);
} else if (eventData.type === 'ArmBot' && eventData) {
const backendEventData = {
type: 'ArmBot',
points: eventData.points,
};
// REST
// await setFloorItemApi(
// organization,
// obj.uuid,
// obj.userData.name,
// obj.userData.modelId,
// [worldPosition.x, worldPosition.y, worldPosition.z],
// { "x": obj.rotation.x, "y": obj.rotation.y, "z": obj.rotation.z },
// false,
// true,
// { type: backendEventData.type, points: backendEventData.points }
// );
//SOCKET
const data = {
organization,
modeluuid: newFloorItem.modeluuid,
modelname: newFloorItem.modelname,
modelfileID: newFloorItem.modelfileID,
position: newFloorItem.position,
rotation: { x: obj.rotation.x, y: obj.rotation.y, z: obj.rotation.z },
isLocked: false,
isVisible: true,
eventData: { type: backendEventData.type, points: backendEventData.points },
socketId: socket.id,
};
const newEventData: any = { type: backendEventData.type, points: backendEventData.points };
newEventData.modeluuid = newFloorItem.modeluuid;
newEventData.modelName = newFloorItem.modelname;
newEventData.position = newFloorItem.position;
newEventData.rotation = [obj.rotation.x, obj.rotation.y, obj.rotation.z];
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | Types.ArmBotEventsSchema)[]) => {
const updatedEvents = (prevEvents || []).map(event =>
event.modeluuid === newFloorItem.modeluuid
? { ...event, ...newEventData }

View File

@@ -184,13 +184,12 @@ function RotateControls({ rotatedObjects, setRotatedObjects, movedObjects, setMo
return updatedItems;
});
let eventData: Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | undefined = simulationStates.find((events) => events.modeluuid === obj.userData.modeluuid);
console.log('eventData: ', eventData);
let eventData: Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | Types.ArmBotEventsSchema | undefined = simulationStates.find((events) => events.modeluuid === obj.userData.modeluuid);
const email = localStorage.getItem("email");
const organization = email ? email.split("@")[1].split(".")[0] : "default";
if (eventData && eventData.type !== 'StaticMachine') {
if (eventData) {
if (eventData.type === 'Conveyor' && eventData) {
const backendEventData = {
@@ -233,9 +232,8 @@ function RotateControls({ rotatedObjects, setRotatedObjects, movedObjects, setMo
newEventData.modelName = newFloorItem.modelname;
newEventData.position = newFloorItem.position;
newEventData.rotation = [obj.rotation.x, obj.rotation.y, obj.rotation.z];
console.log('newEventData: ', newEventData);
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema)[]) => {
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | Types.ArmBotEventsSchema)[]) => {
const updatedEvents = (prevEvents || []).map(event =>
event.modeluuid === newFloorItem.modeluuid
? { ...event, ...newEventData }
@@ -286,8 +284,115 @@ function RotateControls({ rotatedObjects, setRotatedObjects, movedObjects, setMo
newEventData.modeluuid = newFloorItem.modeluuid;
newEventData.modelName = newFloorItem.modelname;
newEventData.position = newFloorItem.position;
newEventData.rotation = [obj.rotation.x, obj.rotation.y, obj.rotation.z];
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema)[]) => {
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | Types.ArmBotEventsSchema)[]) => {
const updatedEvents = (prevEvents || []).map(event =>
event.modeluuid === newFloorItem.modeluuid
? { ...event, ...newEventData }
: event
);
return updatedEvents;
});
socket.emit("v2:model-asset:add", data);
} else if (eventData.type === 'StaticMachine' && eventData) {
const backendEventData = {
type: 'StaticMachine',
points: eventData.points,
};
// REST
// await setFloorItemApi(
// organization,
// obj.uuid,
// obj.userData.name,
// obj.userData.modelId,
// [worldPosition.x, worldPosition.y, worldPosition.z],
// { "x": obj.rotation.x, "y": obj.rotation.y, "z": obj.rotation.z },
// false,
// true,
// { type: backendEventData.type, points: backendEventData.points }
// );
//SOCKET
const data = {
organization,
modeluuid: newFloorItem.modeluuid,
modelname: newFloorItem.modelname,
modelfileID: newFloorItem.modelfileID,
position: newFloorItem.position,
rotation: { x: obj.rotation.x, y: obj.rotation.y, z: obj.rotation.z },
isLocked: false,
isVisible: true,
eventData: { type: backendEventData.type, points: backendEventData.points },
socketId: socket.id,
};
const newEventData: any = { type: backendEventData.type, points: backendEventData.points };
newEventData.modeluuid = newFloorItem.modeluuid;
newEventData.modelName = newFloorItem.modelname;
newEventData.position = newFloorItem.position;
newEventData.rotation = [obj.rotation.x, obj.rotation.y, obj.rotation.z];
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | Types.ArmBotEventsSchema)[]) => {
const updatedEvents = (prevEvents || []).map(event =>
event.modeluuid === newFloorItem.modeluuid
? { ...event, ...newEventData }
: event
);
return updatedEvents;
});
socket.emit("v2:model-asset:add", data);
} else if (eventData.type === 'ArmBot' && eventData) {
const backendEventData = {
type: 'ArmBot',
points: eventData.points,
};
// REST
// await setFloorItemApi(
// organization,
// obj.uuid,
// obj.userData.name,
// obj.userData.modelId,
// [worldPosition.x, worldPosition.y, worldPosition.z],
// { "x": obj.rotation.x, "y": obj.rotation.y, "z": obj.rotation.z },
// false,
// true,
// { type: backendEventData.type, points: backendEventData.points }
// );
//SOCKET
const data = {
organization,
modeluuid: newFloorItem.modeluuid,
modelname: newFloorItem.modelname,
modelfileID: newFloorItem.modelfileID,
position: newFloorItem.position,
rotation: { x: obj.rotation.x, y: obj.rotation.y, z: obj.rotation.z },
isLocked: false,
isVisible: true,
eventData: { type: backendEventData.type, points: backendEventData.points },
socketId: socket.id,
};
const newEventData: any = { type: backendEventData.type, points: backendEventData.points };
newEventData.modeluuid = newFloorItem.modeluuid;
newEventData.modelName = newFloorItem.modelname;
newEventData.position = newFloorItem.position;
newEventData.rotation = [obj.rotation.x, obj.rotation.y, obj.rotation.z];
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | Types.ArmBotEventsSchema)[]) => {
const updatedEvents = (prevEvents || []).map(event =>
event.modeluuid === newFloorItem.modeluuid
? { ...event, ...newEventData }

View File

@@ -122,10 +122,15 @@ const SelectionControls: React.FC = () => {
if (!toggleView && activeModule === "builder") {
helper.enabled = true;
canvasElement.addEventListener("pointerdown", onPointerDown);
canvasElement.addEventListener("pointermove", onPointerMove);
if (duplicatedObjects.length === 0 && pastedObjects.length === 0) {
canvasElement.addEventListener("pointerdown", onPointerDown);
canvasElement.addEventListener("pointermove", onPointerMove);
canvasElement.addEventListener("pointerup", onPointerUp);
} else {
helper.enabled = false;
helper.dispose();
}
canvasElement.addEventListener("contextmenu", onContextMenu);
canvasElement.addEventListener("pointerup", onPointerUp);
canvasElement.addEventListener("keydown", onKeyDown);
} else {
helper.enabled = false;
@@ -240,7 +245,7 @@ const SelectionControls: React.FC = () => {
}
});
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema)[]) => {
setSimulationStates((prevEvents: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | Types.ArmBotEventsSchema)[]) => {
const updatedEvents = (prevEvents || []).filter(event => event.modeluuid !== selectedMesh.uuid);
return updatedEvents;
});

View File

@@ -1,6 +1,6 @@
import { TransformControls } from "@react-three/drei";
import * as THREE from "three";
import { useselectedFloorItem, useObjectPosition, useObjectScale, useObjectRotation, useTransformMode, useFloorItems, useSocketStore, useActiveTool } from "../../../store/store";
import { useSelectedFloorItem, useObjectPosition, useObjectScale, useObjectRotation, useTransformMode, useFloorItems, useSocketStore, useActiveTool } from "../../../store/store";
import { useThree } from "@react-three/fiber";
import * as Types from '../../../types/world/worldTypes';
@@ -8,7 +8,7 @@ import { useEffect } from "react";
export default function TransformControl() {
const state = useThree();
const { selectedFloorItem, setselectedFloorItem } = useselectedFloorItem();
const { selectedFloorItem, setSelectedFloorItem } = useSelectedFloorItem();
const { objectPosition, setObjectPosition } = useObjectPosition();
const { objectScale, setObjectScale } = useObjectScale();
const { objectRotation, setObjectRotation } = useObjectRotation();
@@ -96,7 +96,7 @@ export default function TransformControl() {
const target = (state.controls as any).getTarget(new THREE.Vector3());
(state.controls as any).setTarget(target.x, 0, target.z, true);
}
setselectedFloorItem(null);
setSelectedFloorItem(null);
{
setObjectPosition({ x: undefined, y: undefined, z: undefined });
setObjectScale({ x: undefined, y: undefined, z: undefined });

View File

@@ -6,7 +6,7 @@ import {
useSelectedActionSphere,
useSelectedPath,
useSelectedWallItem,
useselectedFloorItem,
useSelectedFloorItem,
} from "../../../store/store";
import * as Types from "../../../types/world/worldTypes";
import * as CONSTANTS from "../../../types/world/worldConstants";
@@ -15,7 +15,7 @@ import { useEffect } from "react";
export default function PostProcessing() {
const { deletableFloorItem, setDeletableFloorItem } = useDeletableFloorItem();
const { selectedWallItem, setSelectedWallItem } = useSelectedWallItem();
const { selectedFloorItem, setselectedFloorItem } = useselectedFloorItem();
const { selectedFloorItem, setSelectedFloorItem } = useSelectedFloorItem();
const { selectedActionSphere } = useSelectedActionSphere();
const { selectedPath } = useSelectedPath();

View File

@@ -19,6 +19,7 @@ import Simulation from "../simulation/simulation";
// import Simulation from "./simulationtemp/simulation";
import ZoneCentreTarget from "../../components/ui/componets/zoneCameraTarget";
import Dropped3dWidgets from "../../components/ui/componets/Dropped3dWidget";
import ZoneAssets from "../../components/ui/componets/zoneAssets";
export default function Scene() {
const map = useMemo(
@@ -48,6 +49,7 @@ export default function Scene() {
<MeasurementTool />
<World />
<ZoneCentreTarget />
<ZoneAssets />
<Simulation />
<PostProcessing />
{savedTheme !== "dark" ? <Sun /> : <></>}

View File

@@ -1,190 +1,244 @@
import * as THREE from 'three';
import { useEffect, useRef, useState } from 'react';
import { useThree, useFrame } from '@react-three/fiber';
import { useToolMode } from '../../../store/store';
import { Html } from '@react-three/drei';
import * as THREE from "three";
import { useEffect, useRef, useState } from "react";
import { useThree, useFrame } from "@react-three/fiber";
import { useToolMode } from "../../../store/store";
import { Html } from "@react-three/drei";
const MeasurementTool = () => {
const { gl, raycaster, pointer, camera, scene } = useThree();
const { toolMode } = useToolMode();
const { gl, raycaster, pointer, camera, scene } = useThree();
const { toolMode } = useToolMode();
const [points, setPoints] = useState<THREE.Vector3[]>([]);
const [tubeGeometry, setTubeGeometry] = useState<THREE.TubeGeometry | null>(null);
const groupRef = useRef<THREE.Group>(null);
const [startConePosition, setStartConePosition] = useState<THREE.Vector3 | null>(null);
const [endConePosition, setEndConePosition] = useState<THREE.Vector3 | null>(null);
const [startConeQuaternion, setStartConeQuaternion] = useState(new THREE.Quaternion());
const [endConeQuaternion, setEndConeQuaternion] = useState(new THREE.Quaternion());
const [coneSize, setConeSize] = useState({ radius: 0.2, height: 0.5 });
const [points, setPoints] = useState<THREE.Vector3[]>([]);
const [tubeGeometry, setTubeGeometry] = useState<THREE.TubeGeometry | null>(
null
);
const groupRef = useRef<THREE.Group>(null);
const [startConePosition, setStartConePosition] =
useState<THREE.Vector3 | null>(null);
const [endConePosition, setEndConePosition] = useState<THREE.Vector3 | null>(
null
);
const [startConeQuaternion, setStartConeQuaternion] = useState(
new THREE.Quaternion()
);
const [endConeQuaternion, setEndConeQuaternion] = useState(
new THREE.Quaternion()
);
const [coneSize, setConeSize] = useState({ radius: 0.2, height: 0.5 });
const MIN_RADIUS = 0.001,
MAX_RADIUS = 0.1;
const MIN_CONE_RADIUS = 0.01,
MAX_CONE_RADIUS = 0.4;
const MIN_CONE_HEIGHT = 0.035,
MAX_CONE_HEIGHT = 2.0;
const MIN_RADIUS = 0.001, MAX_RADIUS = 0.1;
const MIN_CONE_RADIUS = 0.01, MAX_CONE_RADIUS = 0.4;
const MIN_CONE_HEIGHT = 0.035, MAX_CONE_HEIGHT = 2.0;
useEffect(() => {
const canvasElement = gl.domElement;
let drag = false;
let isLeftMouseDown = false;
useEffect(() => {
const canvasElement = gl.domElement;
let drag = false;
let isLeftMouseDown = false;
const onMouseDown = () => {
isLeftMouseDown = true;
drag = false;
};
const onMouseUp = (evt: any) => {
isLeftMouseDown = false;
if (evt.button === 0 && !drag) {
raycaster.setFromCamera(pointer, camera);
const intersects = raycaster.intersectObjects(scene.children, true).filter(intersect => !intersect.object.name.includes("Roof") && !intersect.object.name.includes("MeasurementReference") && !intersect.object.name.includes("agv-collider") && !(intersect.object.type === "GridHelper"));
if (intersects.length > 0) {
const intersectionPoint = intersects[0].point.clone();
if (points.length < 2) {
setPoints([...points, intersectionPoint]);
} else {
setPoints([intersectionPoint]);
}
}
}
};
const onMouseMove = () => {
if (isLeftMouseDown) drag = true;
};
const onContextMenu = (evt: any) => {
evt.preventDefault();
if (!drag) {
evt.preventDefault();
setPoints([]);
setTubeGeometry(null);
}
};
if (toolMode === "MeasurementScale") {
canvasElement.addEventListener("pointerdown", onMouseDown);
canvasElement.addEventListener("pointermove", onMouseMove);
canvasElement.addEventListener("pointerup", onMouseUp);
canvasElement.addEventListener("contextmenu", onContextMenu);
} else {
resetMeasurement();
setPoints([]);
}
return () => {
canvasElement.removeEventListener("pointerdown", onMouseDown);
canvasElement.removeEventListener("pointermove", onMouseMove);
canvasElement.removeEventListener("pointerup", onMouseUp);
canvasElement.removeEventListener("contextmenu", onContextMenu);
};
}, [toolMode, camera, raycaster, pointer, scene, points]);
useFrame(() => {
if (points.length === 1) {
raycaster.setFromCamera(pointer, camera);
const intersects = raycaster.intersectObjects(scene.children, true).filter(intersect => !intersect.object.name.includes("Roof") && !intersect.object.name.includes("MeasurementReference") && !intersect.object.name.includes("agv-collider") && !(intersect.object.type === "GridHelper"));
if (intersects.length > 0) {
updateMeasurement(points[0], intersects[0].point);
}
} else if (points.length === 2) {
updateMeasurement(points[0], points[1]);
} else {
resetMeasurement();
}
});
const updateMeasurement = (start: THREE.Vector3, end: THREE.Vector3) => {
const distance = start.distanceTo(end);
const radius = THREE.MathUtils.clamp(distance * 0.02, MIN_RADIUS, MAX_RADIUS);
const coneRadius = THREE.MathUtils.clamp(distance * 0.05, MIN_CONE_RADIUS, MAX_CONE_RADIUS);
const coneHeight = THREE.MathUtils.clamp(distance * 0.2, MIN_CONE_HEIGHT, MAX_CONE_HEIGHT);
setConeSize({ radius: coneRadius, height: coneHeight });
const direction = new THREE.Vector3().subVectors(end, start).normalize();
const offset = direction.clone().multiplyScalar(coneHeight * 0.5);
let tubeStart = start.clone().add(offset);
let tubeEnd = end.clone().sub(offset);
tubeStart.y = Math.max(tubeStart.y, 0);
tubeEnd.y = Math.max(tubeEnd.y, 0);
const curve = new THREE.CatmullRomCurve3([tubeStart, tubeEnd]);
setTubeGeometry(new THREE.TubeGeometry(curve, 20, radius, 8, false));
setStartConePosition(tubeStart);
setEndConePosition(tubeEnd);
setStartConeQuaternion(getArrowOrientation(start, end));
setEndConeQuaternion(getArrowOrientation(end, start));
const onMouseDown = () => {
isLeftMouseDown = true;
drag = false;
};
const resetMeasurement = () => {
const onMouseUp = (evt: any) => {
isLeftMouseDown = false;
if (evt.button === 0 && !drag) {
raycaster.setFromCamera(pointer, camera);
const intersects = raycaster
.intersectObjects(scene.children, true)
.filter(
(intersect) =>
!intersect.object.name.includes("Roof") &&
!intersect.object.name.includes("MeasurementReference") &&
!intersect.object.name.includes("agv-collider") &&
!(intersect.object.type === "GridHelper")
);
if (intersects.length > 0) {
const intersectionPoint = intersects[0].point.clone();
if (points.length < 2) {
setPoints([...points, intersectionPoint]);
} else {
setPoints([intersectionPoint]);
}
}
}
};
const onMouseMove = () => {
if (isLeftMouseDown) drag = true;
};
const onContextMenu = (evt: any) => {
evt.preventDefault();
if (!drag) {
evt.preventDefault();
setPoints([]);
setTubeGeometry(null);
setStartConePosition(null);
setEndConePosition(null);
}
};
const getArrowOrientation = (start: THREE.Vector3, end: THREE.Vector3) => {
const direction = new THREE.Vector3().subVectors(end, start).normalize().negate();
const quaternion = new THREE.Quaternion();
quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), direction);
return quaternion;
if (toolMode === "MeasurementScale") {
canvasElement.addEventListener("pointerdown", onMouseDown);
canvasElement.addEventListener("pointermove", onMouseMove);
canvasElement.addEventListener("pointerup", onMouseUp);
canvasElement.addEventListener("contextmenu", onContextMenu);
} else {
resetMeasurement();
setPoints([]);
}
return () => {
canvasElement.removeEventListener("pointerdown", onMouseDown);
canvasElement.removeEventListener("pointermove", onMouseMove);
canvasElement.removeEventListener("pointerup", onMouseUp);
canvasElement.removeEventListener("contextmenu", onContextMenu);
};
}, [toolMode, camera, raycaster, pointer, scene, points]);
useEffect(() => {
if (points.length === 2) {
console.log(points[0].distanceTo(points[1]));
}
}, [points])
useFrame(() => {
if (points.length === 1) {
raycaster.setFromCamera(pointer, camera);
const intersects = raycaster
.intersectObjects(scene.children, true)
.filter(
(intersect) =>
!intersect.object.name.includes("Roof") &&
!intersect.object.name.includes("MeasurementReference") &&
!intersect.object.name.includes("agv-collider") &&
!(intersect.object.type === "GridHelper")
);
return (
<group ref={groupRef} name="MeasurementGroup">
{startConePosition && (
<mesh name='MeasurementReference' position={startConePosition} quaternion={startConeQuaternion}>
<coneGeometry args={[coneSize.radius, coneSize.height, 16]} />
<meshBasicMaterial color="yellow" />
</mesh>
)}
{endConePosition && (
<mesh name='MeasurementReference' position={endConePosition} quaternion={endConeQuaternion}>
<coneGeometry args={[coneSize.radius, coneSize.height, 16]} />
<meshBasicMaterial color="yellow" />
</mesh>
)}
{tubeGeometry && (
<mesh name='MeasurementReference' geometry={tubeGeometry}>
<meshBasicMaterial color="yellow" />
</mesh>
)}
if (intersects.length > 0) {
updateMeasurement(points[0], intersects[0].point);
}
} else if (points.length === 2) {
updateMeasurement(points[0], points[1]);
} else {
resetMeasurement();
}
});
{startConePosition && endConePosition && (
<Html
as="div"
center
zIndexRange={[1, 0]}
style={{
padding: "10px",
color: "white",
borderRadius: "8px",
textAlign: "center",
fontFamily: "Arial, sans-serif",
}}
transform
sprite
scale={THREE.MathUtils.clamp(startConePosition.distanceTo(endConePosition) * 0.25, 0, 10)}
position={[(startConePosition.x + endConePosition.x) / 2, (startConePosition.y + endConePosition.y) / 2, (startConePosition.z + endConePosition.z) / 2]}
>
<div style={{ color: "black" }} >{startConePosition.distanceTo(endConePosition).toFixed(2)} m</div>
</Html>
)}
</group>
const updateMeasurement = (start: THREE.Vector3, end: THREE.Vector3) => {
const distance = start.distanceTo(end);
const radius = THREE.MathUtils.clamp(
distance * 0.02,
MIN_RADIUS,
MAX_RADIUS
);
const coneRadius = THREE.MathUtils.clamp(
distance * 0.05,
MIN_CONE_RADIUS,
MAX_CONE_RADIUS
);
const coneHeight = THREE.MathUtils.clamp(
distance * 0.2,
MIN_CONE_HEIGHT,
MAX_CONE_HEIGHT
);
setConeSize({ radius: coneRadius, height: coneHeight });
const direction = new THREE.Vector3().subVectors(end, start).normalize();
const offset = direction.clone().multiplyScalar(coneHeight * 0.5);
let tubeStart = start.clone().add(offset);
let tubeEnd = end.clone().sub(offset);
tubeStart.y = Math.max(tubeStart.y, 0);
tubeEnd.y = Math.max(tubeEnd.y, 0);
const curve = new THREE.CatmullRomCurve3([tubeStart, tubeEnd]);
setTubeGeometry(new THREE.TubeGeometry(curve, 20, radius, 8, false));
setStartConePosition(tubeStart);
setEndConePosition(tubeEnd);
setStartConeQuaternion(getArrowOrientation(start, end));
setEndConeQuaternion(getArrowOrientation(end, start));
};
const resetMeasurement = () => {
setTubeGeometry(null);
setStartConePosition(null);
setEndConePosition(null);
};
const getArrowOrientation = (start: THREE.Vector3, end: THREE.Vector3) => {
const direction = new THREE.Vector3()
.subVectors(end, start)
.normalize()
.negate();
const quaternion = new THREE.Quaternion();
quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), direction);
return quaternion;
};
useEffect(() => {
if (points.length === 2) {
console.log(points[0].distanceTo(points[1]));
}
}, [points]);
return (
<group ref={groupRef} name="MeasurementGroup">
{startConePosition && (
<mesh
name="MeasurementReference"
position={startConePosition}
quaternion={startConeQuaternion}
>
<coneGeometry args={[coneSize.radius, coneSize.height, 16]} />
<meshBasicMaterial color="yellow" />
</mesh>
)}
{endConePosition && (
<mesh
name="MeasurementReference"
position={endConePosition}
quaternion={endConeQuaternion}
>
<coneGeometry args={[coneSize.radius, coneSize.height, 16]} />
<meshBasicMaterial color="yellow" />
</mesh>
)}
{tubeGeometry && (
<mesh name="MeasurementReference" geometry={tubeGeometry}>
<meshBasicMaterial color="yellow" />
</mesh>
)}
{startConePosition && endConePosition && (
<Html
scale={THREE.MathUtils.clamp(
startConePosition.distanceTo(endConePosition) * 0.25,
0,
10
)}
position={[
(startConePosition.x + endConePosition.x) / 2,
(startConePosition.y + endConePosition.y) / 2,
(startConePosition.z + endConePosition.z) / 2,
]}
// class
wrapperClass="distance-text-wrapper"
className="distance-text"
// other
zIndexRange={[1, 0]}
prepend
sprite
>
<div>
{startConePosition.distanceTo(endConePosition).toFixed(2)} m
</div>
</Html>
)}
</group>
);
};
export default MeasurementTool;

View File

@@ -6,8 +6,8 @@ import { useThree, useFrame } from "@react-three/fiber";
////////// Component Imports //////////
import DistanceText from "../../builder/geomentries/lines/distanceText";
import ReferenceDistanceText from "../../builder/geomentries/lines/referenceDistanceText";
import DistanceText from "../../builder/geomentries/lines/distanceText/distanceText";
import ReferenceDistanceText from "../../builder/geomentries/lines/distanceText/referenceDistanceText";
////////// Assests Imports //////////

View File

@@ -1,9 +1,9 @@
import { useFrame, useThree } from '@react-three/fiber';
import React, { useEffect, useState } from 'react';
import React, { useEffect, useRef, useState } from 'react';
import * as THREE from 'three';
import * as Types from '../../../types/world/worldTypes';
import { QuadraticBezierLine } from '@react-three/drei';
import { useIsConnecting, useSimulationStates, useSocketStore } from '../../../store/store';
import { useDeleteTool, useIsConnecting, useRenderDistance, useSimulationStates, useSocketStore } from '../../../store/store';
import useModuleStore from '../../../store/useModuleStore';
import { usePlayButtonStore } from '../../../store/usePlayButtonStore';
import { setEventApi } from '../../../services/factoryBuilder/assest/floorAsset/setEventsApt';
@@ -11,28 +11,23 @@ import { setEventApi } from '../../../services/factoryBuilder/assest/floorAsset/
function PathConnector({ pathsGroupRef }: { pathsGroupRef: React.MutableRefObject<THREE.Group> }) {
const { activeModule } = useModuleStore();
const { gl, raycaster, scene, pointer, camera } = useThree();
const { deleteTool } = useDeleteTool();
const { renderDistance } = useRenderDistance();
const { setIsConnecting } = useIsConnecting();
const { simulationStates, setSimulationStates } = useSimulationStates();
const { isPlaying } = usePlayButtonStore();
const { socket } = useSocketStore();
const groupRefs = useRef<{ [key: string]: any }>({});
const [firstSelected, setFirstSelected] = useState<{
modelUUID: string;
sphereUUID: string;
position: THREE.Vector3;
isCorner: boolean;
} | null>(null);
const [firstSelected, setFirstSelected] = useState<{ modelUUID: string; sphereUUID: string; position: THREE.Vector3; isCorner: boolean; } | null>(null);
const [currentLine, setCurrentLine] = useState<{ start: THREE.Vector3, end: THREE.Vector3, mid: THREE.Vector3 } | null>(null);
const [helperlineColor, setHelperLineColor] = useState<string>('red');
const [hoveredLineKey, setHoveredLineKey] = useState<string | null>(null);
const updatePathConnections = (
fromModelUUID: string,
fromPointUUID: string,
toModelUUID: string,
toPointUUID: string
) => {
const updatePathConnections = (fromModelUUID: string, fromPointUUID: string, toModelUUID: string, toPointUUID: string) => {
const updatedPaths = simulationStates.map(path => {
if (path.type === 'Conveyor') {
// Handle outgoing connections from Conveyor
if (path.modeluuid === fromModelUUID) {
return {
...path,
@@ -61,6 +56,7 @@ function PathConnector({ pathsGroupRef }: { pathsGroupRef: React.MutableRefObjec
})
};
}
// Handle incoming connections to Conveyor
else if (path.modeluuid === toModelUUID) {
return {
...path,
@@ -167,82 +163,170 @@ function PathConnector({ pathsGroupRef }: { pathsGroupRef: React.MutableRefObjec
}
return path;
}
// else if (path.type === 'StaticMachine') {
// if (path.modeluuid === fromModelUUID && path.points.uuid === fromPointUUID) {
// const newTarget = {
// modelUUID: toModelUUID,
// pointUUID: toPointUUID
// };
// const existingTargets = path.points.connections.targets || [];
else if (path.type === 'StaticMachine') {
// Handle outgoing connections from StaticMachine
if (path.modeluuid === fromModelUUID && path.points.uuid === fromPointUUID) {
const newTarget = {
modelUUID: toModelUUID,
pointUUID: toPointUUID
};
// // Check if target is an ArmBot
// const toPath = simulationStates.find(p => p.modeluuid === toModelUUID);
// if (toPath?.type !== 'ArmBot') {
// console.log("StaticMachine can only connect to ArmBot");
// return path;
// }
// Ensure target is an ArmBot
const toPath = simulationStates.find(p => p.modeluuid === toModelUUID);
if (toPath?.type !== 'ArmBot') {
console.log("StaticMachine can only connect to ArmBot");
return path;
}
// // Check if already has a connection
// if (existingTargets.length >= 1) {
// console.log("StaticMachine can have only one connection");
// return path;
// }
const existingTargets = path.points.connections.targets || [];
// if (!existingTargets.some(target =>
// target.modelUUID === newTarget.modelUUID &&
// target.pointUUID === newTarget.pointUUID
// )) {
// return {
// ...path,
// points: {
// ...path.points,
// connections: {
// ...path.points.connections,
// targets: [...existingTargets, newTarget]
// }
// }
// };
// }
// }
// // Handle incoming connections to StaticMachine
// else if (path.modeluuid === toModelUUID && path.points.uuid === toPointUUID) {
// const reverseTarget = {
// modelUUID: fromModelUUID,
// pointUUID: fromPointUUID
// };
// const existingTargets = path.points.connections.targets || [];
// Allow only one connection
if (existingTargets.length >= 1) {
console.log("StaticMachine can only have one connection");
return path;
}
// // Check if source is an ArmBot
// const fromPath = simulationStates.find(p => p.modeluuid === fromModelUUID);
// if (fromPath?.type !== 'ArmBot') {
// console.log("StaticMachine can only connect to ArmBot");
// return path;
// }
if (!existingTargets.some(target =>
target.modelUUID === newTarget.modelUUID &&
target.pointUUID === newTarget.pointUUID
)) {
return {
...path,
points: {
...path.points,
connections: {
...path.points.connections,
targets: [...existingTargets, newTarget]
}
}
};
}
}
// // Check if already has a connection
// if (existingTargets.length >= 1) {
// console.log("StaticMachine can have only one connection");
// return path;
// }
// Handle incoming connections to StaticMachine
else if (path.modeluuid === toModelUUID && path.points.uuid === toPointUUID) {
const reverseTarget = {
modelUUID: fromModelUUID,
pointUUID: fromPointUUID
};
const fromPath = simulationStates.find(p => p.modeluuid === fromModelUUID);
if (fromPath?.type !== 'ArmBot') {
console.log("StaticMachine can only be connected from ArmBot");
return path;
}
const existingTargets = path.points.connections.targets || [];
if (existingTargets.length >= 1) {
console.log("StaticMachine can only have one connection");
return path;
}
if (!existingTargets.some(target =>
target.modelUUID === reverseTarget.modelUUID &&
target.pointUUID === reverseTarget.pointUUID
)) {
return {
...path,
points: {
...path.points,
connections: {
...path.points.connections,
targets: [...existingTargets, reverseTarget]
}
}
};
}
}
return path;
}
else if (path.type === 'ArmBot') {
// Handle outgoing connections from ArmBot
if (path.modeluuid === fromModelUUID && path.points.uuid === fromPointUUID) {
const newTarget = {
modelUUID: toModelUUID,
pointUUID: toPointUUID
};
const toPath = simulationStates.find(p => p.modeluuid === toModelUUID);
if (!toPath) return path;
const existingTargets = path.points.connections.targets || [];
// Check if connecting to a StaticMachine and already connected to one
const alreadyConnectedToStatic = existingTargets.some(target => {
const targetPath = simulationStates.find(p => p.modeluuid === target.modelUUID);
return targetPath?.type === 'StaticMachine';
});
if (toPath.type === 'StaticMachine') {
if (alreadyConnectedToStatic) {
console.log("ArmBot can only connect to one StaticMachine");
return path;
}
}
if (!existingTargets.some(target =>
target.modelUUID === newTarget.modelUUID &&
target.pointUUID === newTarget.pointUUID
)) {
return {
...path,
points: {
...path.points,
connections: {
...path.points.connections,
targets: [...existingTargets, newTarget]
}
}
};
}
}
// Handle incoming connections to ArmBot
else if (path.modeluuid === toModelUUID && path.points.uuid === toPointUUID) {
const reverseTarget = {
modelUUID: fromModelUUID,
pointUUID: fromPointUUID
};
const fromPath = simulationStates.find(p => p.modeluuid === fromModelUUID);
if (!fromPath) return path;
const existingTargets = path.points.connections.targets || [];
const alreadyConnectedFromStatic = existingTargets.some(target => {
const targetPath = simulationStates.find(p => p.modeluuid === target.modelUUID);
return targetPath?.type === 'StaticMachine';
});
if (fromPath.type === 'StaticMachine') {
if (alreadyConnectedFromStatic) {
console.log("ArmBot can only be connected from one StaticMachine");
return path;
}
}
if (!existingTargets.some(target =>
target.modelUUID === reverseTarget.modelUUID &&
target.pointUUID === reverseTarget.pointUUID
)) {
return {
...path,
points: {
...path.points,
connections: {
...path.points.connections,
targets: [...existingTargets, reverseTarget]
}
}
};
}
}
return path;
}
// if (!existingTargets.some(target =>
// target.modelUUID === reverseTarget.modelUUID &&
// target.pointUUID === reverseTarget.pointUUID
// )) {
// return {
// ...path,
// points: {
// ...path.points,
// connections: {
// ...path.points.connections,
// targets: [...existingTargets, reverseTarget]
// }
// }
// };
// }
// }
// return path;
// }
return path;
});
@@ -255,7 +339,7 @@ function PathConnector({ pathsGroupRef }: { pathsGroupRef: React.MutableRefObjec
updateBackend(updatedPathDetails);
};
const updateBackend = async (updatedPaths: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema)[]) => {
const updateBackend = async (updatedPaths: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | Types.ArmBotEventsSchema)[]) => {
if (updatedPaths.length === 0) return;
const email = localStorage.getItem("email");
const organization = email ? email.split("@")[1].split(".")[0] : "";
@@ -293,6 +377,38 @@ function PathConnector({ pathsGroupRef }: { pathsGroupRef: React.MutableRefObjec
socket.emit('v2:model-asset:updateEventData', data);
} else if (updatedPath.type === 'StaticMachine') {
// await setEventApi(
// organization,
// updatedPath.modeluuid,
// { type: "StaticMachine", points: updatedPath.points }
// );
const data = {
organization: organization,
modeluuid: updatedPath.modeluuid,
eventData: { type: "StaticMachine", points: updatedPath.points }
}
socket.emit('v2:model-asset:updateEventData', data);
} else if (updatedPath.type === 'ArmBot') {
// await setEventApi(
// organization,
// updatedPath.modeluuid,
// { type: "ArmBot", points: updatedPath.points }
// );
const data = {
organization: organization,
modeluuid: updatedPath.modeluuid,
eventData: { type: "ArmBot", points: updatedPath.points }
}
socket.emit('v2:model-asset:updateEventData', data);
}
})
@@ -397,7 +513,6 @@ function PathConnector({ pathsGroupRef }: { pathsGroupRef: React.MutableRefObjec
// For Vehicles, check if they're already connected to anything
if (intersected.userData.path.type === 'Vehicle') {
console.log('intersected: ', intersected);
const vehicleConnections = intersected.userData.path.points.connections.targets.length;
if (vehicleConnections >= 1) {
console.log("Vehicle can only have one connection");
@@ -437,6 +552,69 @@ function PathConnector({ pathsGroupRef }: { pathsGroupRef: React.MutableRefObjec
return;
}
// Check if StaticMachine is involved in the connection
if ((firstPath?.type === 'StaticMachine' && secondPath?.type !== 'ArmBot') ||
(secondPath?.type === 'StaticMachine' && firstPath?.type !== 'ArmBot')) {
console.log("StaticMachine can only connect to ArmBot");
return;
}
// Check if StaticMachine already has a connection
if (firstPath?.type === 'StaticMachine') {
const staticConnections = firstPath.points.connections.targets.length;
if (staticConnections >= 1) {
console.log("StaticMachine can only have one connection");
return;
}
}
if (secondPath?.type === 'StaticMachine') {
const staticConnections = secondPath.points.connections.targets.length;
if (staticConnections >= 1) {
console.log("StaticMachine can only have one connection");
return;
}
}
// Check if ArmBot is involved
if ((firstPath?.type === 'ArmBot' && secondPath?.type === 'StaticMachine') ||
(secondPath?.type === 'ArmBot' && firstPath?.type === 'StaticMachine')) {
const armBotPath = firstPath?.type === 'ArmBot' ? firstPath : secondPath;
const staticPath = firstPath?.type === 'StaticMachine' ? firstPath : secondPath;
const armBotConnections = armBotPath.points.connections.targets || [];
const alreadyConnectedToStatic = armBotConnections.some(target => {
const targetPath = simulationStates.find(p => p.modeluuid === target.modelUUID);
return targetPath?.type === 'StaticMachine';
});
if (alreadyConnectedToStatic) {
console.log("ArmBot can only connect to one StaticMachine");
return;
}
const staticConnections = staticPath.points.connections.targets.length;
if (staticConnections >= 1) {
console.log("StaticMachine can only have one connection");
return;
}
}
// Prevent ArmBot ↔ ArmBot
if (firstPath?.type === 'ArmBot' && secondPath?.type === 'ArmBot') {
console.log("Cannot connect two ArmBots together");
return;
}
// If one is ArmBot, ensure the other is StaticMachine or Conveyor
if (firstPath?.type === 'ArmBot' || secondPath?.type === 'ArmBot') {
const otherType = firstPath?.type === 'ArmBot' ? secondPath?.type : firstPath?.type;
if (otherType !== 'StaticMachine' && otherType !== 'Conveyor') {
console.log("ArmBot can only connect to Conveyors or one StaticMachine");
return;
}
}
// At least one must be start/end point
if (!firstSelected.isCorner && !isStartOrEnd) {
console.log("At least one of the selected spheres must be a start or end point.");
@@ -444,20 +622,10 @@ function PathConnector({ pathsGroupRef }: { pathsGroupRef: React.MutableRefObjec
}
// All checks passed - make the connection
handleAddConnection(
firstSelected.modelUUID,
firstSelected.sphereUUID,
modelUUID,
sphereUUID
);
handleAddConnection(firstSelected.modelUUID, firstSelected.sphereUUID, modelUUID, sphereUUID);
} else {
// First selection - just store it
setFirstSelected({
modelUUID,
sphereUUID,
position: worldPosition,
isCorner: isStartOrEnd
});
setFirstSelected({ modelUUID, sphereUUID, position: worldPosition, isCorner: isStartOrEnd });
setIsConnecting(true);
}
}
@@ -470,7 +638,7 @@ function PathConnector({ pathsGroupRef }: { pathsGroupRef: React.MutableRefObjec
}
};
if (activeModule === 'simulation') {
if (activeModule === 'simulation' && !deleteTool) {
canvasElement.addEventListener("mousedown", onMouseDown);
canvasElement.addEventListener("mouseup", onMouseUp);
canvasElement.addEventListener("mousemove", onMouseMove);
@@ -487,7 +655,16 @@ function PathConnector({ pathsGroupRef }: { pathsGroupRef: React.MutableRefObjec
canvasElement.removeEventListener("mousemove", onMouseMove);
canvasElement.removeEventListener("contextmenu", onContextMenu);
};
}, [camera, scene, raycaster, firstSelected, simulationStates]);
}, [camera, scene, raycaster, firstSelected, simulationStates, deleteTool]);
useFrame(() => {
Object.values(groupRefs.current).forEach((group) => {
if (group) {
const distance = new THREE.Vector3(...group.position.toArray()).distanceTo(camera.position);
group.visible = ((distance <= renderDistance) && !isPlaying);
}
});
});
useFrame(() => {
if (firstSelected) {
@@ -511,9 +688,7 @@ function PathConnector({ pathsGroupRef }: { pathsGroupRef: React.MutableRefObjec
}
}
const sphereIntersects = raycaster.intersectObjects(pathsGroupRef.current.children, true).filter((obj) =>
obj.object.name.includes("events-sphere")
);
const sphereIntersects = raycaster.intersectObjects(pathsGroupRef.current.children, true).filter((obj) => obj.object.name.includes("events-sphere"));
if (sphereIntersects.length > 0) {
const sphere = sphereIntersects[0].object;
@@ -528,15 +703,21 @@ function PathConnector({ pathsGroupRef }: { pathsGroupRef: React.MutableRefObjec
const isVehicleToVehicle = firstPath?.type === 'Vehicle' && secondPath?.type === 'Vehicle';
// Inside the useFrame hook, where we check for snapped spheres:
const isConnectable = (pathData.type === 'Vehicle' ||
const isConnectable = (
pathData.type === 'Vehicle' ||
pathData.type === 'ArmBot' ||
(pathData.points.length > 0 && (
sphereUUID === pathData.points[0].uuid ||
sphereUUID === pathData.points[pathData.points.length - 1].uuid
))) &&
sphereUUID === pathData.points[pathData.points.length - 1].uuid ||
(pathData.type === 'Conveyor' && firstPath?.type === 'ArmBot') // Allow ArmBot to connect to middle points
))
) &&
!isVehicleToVehicle &&
!(firstPath?.type === 'Conveyor' &&
!(
firstPath?.type === 'Conveyor' &&
pathData.type === 'Conveyor' &&
!firstSelected.isCorner);
!firstSelected.isCorner
);
// Check for duplicate connection (regardless of path type)
const isDuplicateConnection = simulationStates.some(path => {
@@ -574,12 +755,50 @@ function PathConnector({ pathsGroupRef }: { pathsGroupRef: React.MutableRefObjec
(firstPath?.type === 'Vehicle' && secondPath?.type !== 'Conveyor') ||
(secondPath?.type === 'Vehicle' && firstPath?.type !== 'Conveyor');
// Check if StaticMachine is connecting to non-ArmBot
const isStaticMachineToNonArmBot =
(firstPath?.type === 'StaticMachine' && secondPath?.type !== 'ArmBot') ||
(secondPath?.type === 'StaticMachine' && firstPath?.type !== 'ArmBot');
// Check if StaticMachine already has a connection
const isStaticMachineAtMaxConnections =
(firstPath?.type === 'StaticMachine' && firstPath.points.connections.targets.length >= 1) ||
(secondPath?.type === 'StaticMachine' && secondPath.points.connections.targets.length >= 1);
// Check if ArmBot is connecting to StaticMachine
const isArmBotToStaticMachine =
(firstPath?.type === 'ArmBot' && secondPath?.type === 'StaticMachine') ||
(secondPath?.type === 'ArmBot' && firstPath?.type === 'StaticMachine');
// Prevent multiple StaticMachine connections to ArmBot
let isArmBotAlreadyConnectedToStatic = false;
if (isArmBotToStaticMachine) {
const armBotPath = firstPath?.type === 'ArmBot' ? firstPath : secondPath;
isArmBotAlreadyConnectedToStatic = armBotPath.points.connections.targets.some(target => {
const targetPath = simulationStates.find(p => p.modeluuid === target.modelUUID);
return targetPath?.type === 'StaticMachine';
});
}
// Prevent ArmBot to ArmBot
const isArmBotToArmBot = firstPath?.type === 'ArmBot' && secondPath?.type === 'ArmBot';
// If ArmBot is involved, other must be Conveyor or StaticMachine
const isArmBotToInvalidType = (firstPath?.type === 'ArmBot' || secondPath?.type === 'ArmBot') &&
!(firstPath?.type === 'Conveyor' || firstPath?.type === 'StaticMachine' ||
secondPath?.type === 'Conveyor' || secondPath?.type === 'StaticMachine');
if (
!isDuplicateConnection &&
!isVehicleToVehicle &&
!isNonVehicleAlreadyConnected &&
!isVehicleAtMaxConnections &&
!isVehicleConnectingToNonConveyor &&
!isStaticMachineToNonArmBot &&
!isStaticMachineAtMaxConnections &&
!isArmBotToArmBot &&
!isArmBotToInvalidType &&
!isArmBotAlreadyConnectedToStatic &&
firstSelected.sphereUUID !== sphereUUID &&
firstSelected.modelUUID !== modelUUID &&
(firstSelected.isCorner || isConnectable) &&
@@ -596,6 +815,7 @@ function PathConnector({ pathsGroupRef }: { pathsGroupRef: React.MutableRefObjec
} else {
isInvalidConnection = true;
}
}
if (snappedSphere) {
@@ -632,14 +852,144 @@ function PathConnector({ pathsGroupRef }: { pathsGroupRef: React.MutableRefObjec
}
});
const removeConnections = (connection1: { model: string; point: string }, connection2: { model: string; point: string }) => {
const updatedStates = simulationStates.map(state => {
// Handle Conveyor (which has multiple points)
if (state.type === 'Conveyor') {
const updatedConveyor: Types.ConveyorEventsSchema = {
...state,
points: state.points.map(point => {
// Check if this point is either connection1 or connection2
if ((state.modeluuid === connection1.model && point.uuid === connection1.point) ||
(state.modeluuid === connection2.model && point.uuid === connection2.point)) {
return {
...point,
connections: {
...point.connections,
targets: point.connections.targets.filter(target => {
// Remove the target that matches the other connection
return !(
(target.modelUUID === connection1.model && target.pointUUID === connection1.point) ||
(target.modelUUID === connection2.model && target.pointUUID === connection2.point)
);
})
}
};
}
return point;
})
};
return updatedConveyor;
}
// Handle Vehicle
else if (state.type === 'Vehicle') {
if ((state.modeluuid === connection1.model && state.points.uuid === connection1.point) ||
(state.modeluuid === connection2.model && state.points.uuid === connection2.point)) {
const updatedVehicle: Types.VehicleEventsSchema = {
...state,
points: {
...state.points,
connections: {
...state.points.connections,
targets: state.points.connections.targets.filter(target => {
return !(
(target.modelUUID === connection1.model && target.pointUUID === connection1.point) ||
(target.modelUUID === connection2.model && target.pointUUID === connection2.point)
);
})
},
// Ensure all required Vehicle point properties are included
speed: state.points.speed,
actions: state.points.actions
}
};
return updatedVehicle;
}
}
// Handle StaticMachine
else if (state.type === 'StaticMachine') {
if ((state.modeluuid === connection1.model && state.points.uuid === connection1.point) ||
(state.modeluuid === connection2.model && state.points.uuid === connection2.point)) {
const updatedStaticMachine: Types.StaticMachineEventsSchema = {
...state,
points: {
...state.points,
connections: {
...state.points.connections,
targets: state.points.connections.targets.filter(target => {
return !(
(target.modelUUID === connection1.model && target.pointUUID === connection1.point) ||
(target.modelUUID === connection2.model && target.pointUUID === connection2.point)
);
})
},
// Ensure all required StaticMachine point properties are included
actions: state.points.actions,
triggers: state.points.triggers
}
};
return updatedStaticMachine;
}
}
// Handle ArmBot
else if (state.type === 'ArmBot') {
if ((state.modeluuid === connection1.model && state.points.uuid === connection1.point) ||
(state.modeluuid === connection2.model && state.points.uuid === connection2.point)) {
const updatedArmBot: Types.ArmBotEventsSchema = {
...state,
points: {
...state.points,
connections: {
...state.points.connections,
targets: state.points.connections.targets.filter(target => {
return !(
(target.modelUUID === connection1.model && target.pointUUID === connection1.point) ||
(target.modelUUID === connection2.model && target.pointUUID === connection2.point)
);
})
},
actions: {
...state.points.actions,
processes: state.points.actions.processes?.filter(process => {
return !(
process.startPoint === connection1.point ||
process.endPoint === connection1.point ||
process.startPoint === connection2.point ||
process.endPoint === connection2.point
);
}) || []
},
triggers: state.points.triggers
}
};
return updatedArmBot;
}
}
return state;
});
const updatedPaths = updatedStates.filter(state =>
state.modeluuid === connection1.model || state.modeluuid === connection2.model
);
updateBackend(updatedPaths);
setSimulationStates(updatedStates);
};
return (
<group name='simulationConnectionGroup' visible={!isPlaying} >
<group name='simulationConnectionGroup' visible={!isPlaying}>
{simulationStates.flatMap(path => {
if (path.type === 'Conveyor') {
return path.points.flatMap(point =>
point.connections.targets.map((target, index) => {
const targetPath = simulationStates.find(p => p.modeluuid === target.modelUUID);
if (targetPath?.type === 'Vehicle') return null;
if (targetPath?.type !== 'Conveyor' && targetPath?.type !== 'ArmBot') return null;
const fromSphere = pathsGroupRef.current?.getObjectByProperty('uuid', point.uuid);
const toSphere = pathsGroupRef.current?.getObjectByProperty('uuid', target.pointUUID);
@@ -652,31 +1002,48 @@ function PathConnector({ pathsGroupRef }: { pathsGroupRef: React.MutableRefObjec
const distance = fromWorldPosition.distanceTo(toWorldPosition);
const heightFactor = Math.max(0.5, distance * 0.2);
const midPoint = new THREE.Vector3(
(fromWorldPosition.x + toWorldPosition.x) / 2,
Math.max(fromWorldPosition.y, toWorldPosition.y) + heightFactor,
(fromWorldPosition.z + toWorldPosition.z) / 2
);
const midPoint = new THREE.Vector3((fromWorldPosition.x + toWorldPosition.x) / 2, Math.max(fromWorldPosition.y, toWorldPosition.y) + heightFactor, (fromWorldPosition.z + toWorldPosition.z) / 2);
return (
<QuadraticBezierLine
key={`${point.uuid}-${target.pointUUID}-${index}`}
ref={(el) => (groupRefs.current[`${point.uuid}-${target.pointUUID}-${index}`] = el!)}
start={fromWorldPosition.toArray()}
end={toWorldPosition.toArray()}
mid={midPoint.toArray()}
color="white"
color={
deleteTool && hoveredLineKey === `${point.uuid}-${target.pointUUID}-${index}`
? 'red'
: targetPath?.type === 'ArmBot'
? '#42a5f5'
: 'white'
}
lineWidth={4}
dashed
dashed={(deleteTool && hoveredLineKey === `${point.uuid}-${target.pointUUID}-${index}`) ? false : true}
dashSize={0.75}
dashScale={20}
onPointerOver={() => setHoveredLineKey(`${point.uuid}-${target.pointUUID}-${index}`)}
onPointerOut={() => setHoveredLineKey(null)}
onClick={() => {
if (deleteTool) {
const connection1 = { model: path.modeluuid, point: point.uuid }
const connection2 = { model: target.modelUUID, point: target.pointUUID }
removeConnections(connection1, connection2)
}
}}
userData={target}
/>
);
}
return null;
})
);
} else if (path.type === 'Vehicle') {
}
if (path.type === 'Vehicle') {
return path.points.connections.targets.map((target, index) => {
const fromSphere = pathsGroupRef.current?.getObjectByProperty('uuid', path.points.uuid);
const toSphere = pathsGroupRef.current?.getObjectByProperty('uuid', target.pointUUID);
@@ -689,30 +1056,97 @@ function PathConnector({ pathsGroupRef }: { pathsGroupRef: React.MutableRefObjec
const distance = fromWorldPosition.distanceTo(toWorldPosition);
const heightFactor = Math.max(0.5, distance * 0.2);
const midPoint = new THREE.Vector3(
(fromWorldPosition.x + toWorldPosition.x) / 2,
Math.max(fromWorldPosition.y, toWorldPosition.y) + heightFactor,
(fromWorldPosition.z + toWorldPosition.z) / 2
);
const midPoint = new THREE.Vector3((fromWorldPosition.x + toWorldPosition.x) / 2, Math.max(fromWorldPosition.y, toWorldPosition.y) + heightFactor, (fromWorldPosition.z + toWorldPosition.z) / 2);
return (
<QuadraticBezierLine
key={`${path.points.uuid}-${target.pointUUID}-${index}`}
ref={(el) => (groupRefs.current[`${path.points.uuid}-${target.pointUUID}-${index}`] = el!)}
start={fromWorldPosition.toArray()}
end={toWorldPosition.toArray()}
mid={midPoint.toArray()}
color="orange"
color={
deleteTool && hoveredLineKey === `${path.points.uuid}-${target.pointUUID}-${index}`
? 'red'
: 'orange'
}
lineWidth={4}
dashed
dashed={(deleteTool && hoveredLineKey === `${path.points.uuid}-${target.pointUUID}-${index}`) ? false : true}
dashSize={0.75}
dashScale={20}
onPointerOver={() => setHoveredLineKey(`${path.points.uuid}-${target.pointUUID}-${index}`)}
onPointerOut={() => setHoveredLineKey(null)}
onClick={() => {
if (deleteTool) {
const connection1 = { model: path.modeluuid, point: path.points.uuid }
const connection2 = { model: target.modelUUID, point: target.pointUUID }
removeConnections(connection1, connection2)
}
}}
userData={target}
/>
);
}
return null;
});
}
if (path.type === 'StaticMachine') {
return path.points.connections.targets.map((target, index) => {
const targetPath = simulationStates.find(p => p.modeluuid === target.modelUUID);
if (targetPath?.type !== 'ArmBot') return null;
const fromSphere = pathsGroupRef.current?.getObjectByProperty('uuid', path.points.uuid);
const toSphere = pathsGroupRef.current?.getObjectByProperty('uuid', target.pointUUID);
if (fromSphere && toSphere) {
const fromWorldPosition = new THREE.Vector3();
const toWorldPosition = new THREE.Vector3();
fromSphere.getWorldPosition(fromWorldPosition);
toSphere.getWorldPosition(toWorldPosition);
const distance = fromWorldPosition.distanceTo(toWorldPosition);
const heightFactor = Math.max(0.5, distance * 0.2);
const midPoint = new THREE.Vector3((fromWorldPosition.x + toWorldPosition.x) / 2, Math.max(fromWorldPosition.y, toWorldPosition.y) + heightFactor, (fromWorldPosition.z + toWorldPosition.z) / 2);
return (
<QuadraticBezierLine
key={`${path.points.uuid}-${target.pointUUID}-${index}`}
ref={(el) => (groupRefs.current[`${path.points.uuid}-${target.pointUUID}-${index}`] = el!)}
start={fromWorldPosition.toArray()}
end={toWorldPosition.toArray()}
mid={midPoint.toArray()}
color={
deleteTool && hoveredLineKey === `${path.points.uuid}-${target.pointUUID}-${index}`
? 'red'
: '#42a5f5'
}
lineWidth={4}
dashed={(deleteTool && hoveredLineKey === `${path.points.uuid}-${target.pointUUID}-${index}`) ? false : true}
dashSize={0.75}
dashScale={20}
onPointerOver={() => setHoveredLineKey(`${path.points.uuid}-${target.pointUUID}-${index}`)}
onPointerOut={() => setHoveredLineKey(null)}
onClick={() => {
if (deleteTool) {
const connection1 = { model: path.modeluuid, point: path.points.uuid }
const connection2 = { model: target.modelUUID, point: target.pointUUID }
removeConnections(connection1, connection2)
}
}}
userData={target}
/>
);
}
return null;
});
}
return [];
})}
@@ -730,6 +1164,7 @@ function PathConnector({ pathsGroupRef }: { pathsGroupRef: React.MutableRefObjec
)}
</group>
);
}
export default PathConnector;

View File

@@ -206,6 +206,7 @@ function PathCreation({ pathsGroupRef, }: { pathsGroupRef: React.MutableRefObjec
return (
<group
name={`${path.modeluuid}-${path.type}-path`}
uuid={path.modeluuid}
key={path.modeluuid}
ref={(el) => (groupRefs.current[path.modeluuid] = el!)}
position={path.position}
@@ -271,10 +272,11 @@ function PathCreation({ pathsGroupRef, }: { pathsGroupRef: React.MutableRefObjec
})}
</group>
);
} else if (path.type === "Vehicle" || path.type === "StaticMachine") {
} else if (path.type === "Vehicle") {
return (
<group
name={`${path.modeluuid}-${path.type}-path`}
uuid={path.modeluuid}
key={path.modeluuid}
ref={(el) => (groupRefs.current[path.modeluuid] = el!)}
position={path.position}
@@ -323,6 +325,112 @@ function PathCreation({ pathsGroupRef, }: { pathsGroupRef: React.MutableRefObjec
</Sphere>
</group>
);
} else if (path.type === "StaticMachine") {
return (
<group
name={`${path.modeluuid}-${path.type}-path`}
uuid={path.modeluuid}
key={path.modeluuid}
ref={(el) => (groupRefs.current[path.modeluuid] = el!)}
position={path.position}
onClick={(e) => {
if (isConnecting || eyeDropMode) return;
e.stopPropagation();
setSelectedPath({
path,
group: groupRefs.current[path.modeluuid],
});
setSelectedActionSphere(null);
setTransformMode(null);
setSubModule("mechanics");
}}
onPointerMissed={() => {
if (eyeDropMode) return;
setSelectedPath(null);
setSubModule("properties");
}}
>
<Sphere
key={path.points.uuid}
uuid={path.points.uuid}
position={path.points.position}
args={[0.15, 32, 32]}
name="events-sphere"
ref={(el) => (sphereRefs.current[path.points.uuid] = el!)}
onClick={(e) => {
if (isConnecting || eyeDropMode) return;
e.stopPropagation();
setSelectedActionSphere({
path,
points: sphereRefs.current[path.points.uuid],
});
setSubModule("mechanics");
setSelectedPath(null);
}}
userData={{ points: path.points, path }}
onPointerMissed={() => {
if (eyeDropMode) return;
setSubModule("properties");
setSelectedActionSphere(null);
}}
>
<meshStandardMaterial color="yellow" />
</Sphere>
</group>
);
} else if (path.type === "ArmBot") {
return (
<group
name={`${path.modeluuid}-${path.type}-path`}
uuid={path.modeluuid}
key={path.modeluuid}
ref={(el) => (groupRefs.current[path.modeluuid] = el!)}
position={path.position}
onClick={(e) => {
if (isConnecting || eyeDropMode) return;
e.stopPropagation();
setSelectedPath({
path,
group: groupRefs.current[path.modeluuid],
});
setSelectedActionSphere(null);
setTransformMode(null);
setSubModule("mechanics");
}}
onPointerMissed={() => {
if (eyeDropMode) return;
setSelectedPath(null);
setSubModule("properties");
}}
>
<Sphere
key={path.points.uuid}
uuid={path.points.uuid}
position={path.points.position}
args={[0.15, 32, 32]}
name="events-sphere"
ref={(el) => (sphereRefs.current[path.points.uuid] = el!)}
onClick={(e) => {
if (isConnecting || eyeDropMode) return;
e.stopPropagation();
setSelectedActionSphere({
path,
points: sphereRefs.current[path.points.uuid],
});
setSubModule("mechanics");
setSelectedPath(null);
}}
userData={{ points: path.points, path }}
onPointerMissed={() => {
if (eyeDropMode) return;
setSubModule("properties");
setSelectedActionSphere(null);
}}
>
<meshStandardMaterial color="pink" />
</Sphere>
</group>
);
}
return null;
})}

View File

@@ -9,17 +9,20 @@ import { useProcessAnimation } from "./useProcessAnimations";
import ProcessObject from "./processObject";
import { ProcessData } from "./types";
import { useSimulationStates } from "../../../store/store";
import { retrieveGLTF } from "../../../utils/indexDB/idbUtils";
interface ProcessContainerProps {
processes: ProcessData[];
setProcesses: React.Dispatch<React.SetStateAction<any[]>>;
agvRef: any;
MaterialRef: any;
}
const ProcessAnimator: React.FC<ProcessContainerProps> = ({
processes,
setProcesses,
agvRef,
MaterialRef,
}) => {
const gltf = useLoader(GLTFLoader, crate) as GLTF;
const groupRef = useRef<THREE.Group>(null);
@@ -44,11 +47,57 @@ const ProcessAnimator: React.FC<ProcessContainerProps> = ({
() => ({
Box: new THREE.MeshStandardMaterial({ color: 0x8b4513 }),
Crate: new THREE.MeshStandardMaterial({ color: 0x00ff00 }),
Default: new THREE.MeshStandardMaterial({ color: 0x00ff00 }),
// Default: new THREE.MeshStandardMaterial({ color: 0x00ff00 }),
Default: new THREE.MeshStandardMaterial(),
}),
[]
);
useEffect(() => {
// Update material references for all spawned objects
Object.entries(animationStates).forEach(([processId, processState]) => {
Object.keys(processState.spawnedObjects).forEach((objectId) => {
const entry = {
processId,
objectId,
};
const materialType =
processState.spawnedObjects[objectId]?.currentMaterialType;
if (!materialType) {
return;
}
const matRefArray = MaterialRef.current;
// Find existing material group
const existing = matRefArray.find(
(entryGroup: { material: string; objects: any[] }) =>
entryGroup.material === materialType
);
if (existing) {
// Check if this processId + objectId already exists
const alreadyExists = existing.objects.some(
(o: any) =>
o.processId === entry.processId && o.objectId === entry.objectId
);
if (!alreadyExists) {
existing.objects.push(entry);
}
} else {
// Create new group for this material type
matRefArray.push({
material: materialType,
objects: [entry],
});
}
});
});
}, [animationStates, MaterialRef, agvRef]);
// In processAnimator.tsx - only the relevant spawn logic part that needs fixes
useFrame(() => {
@@ -252,14 +301,39 @@ const ProcessAnimator: React.FC<ProcessContainerProps> = ({
const nextPointIdx = stateRef.currentIndex + 1;
const isLastPoint = nextPointIdx >= path.length;
// if (isLastPoint) {
// if (currentPointData?.actions) {
// const shouldStop = !hasNonInheritActions(
// currentPointData.actions
// );
// if (shouldStop) {
// return;
// }
// }
// }
if (isLastPoint) {
if (currentPointData?.actions) {
const shouldStop = !hasNonInheritActions(
const hasNonInherit = hasNonInheritActions(
currentPointData.actions
);
if (shouldStop) {
if (!hasNonInherit) {
// Remove the object if all actions are inherit
updatedObjects[objectId] = {
...obj,
visible: false,
state: { ...stateRef, isAnimating: false },
};
return;
}
} else {
// No actions at last point - remove the object
updatedObjects[objectId] = {
...obj,
visible: false,
state: { ...stateRef, isAnimating: false },
};
return;
}
}
@@ -329,6 +403,7 @@ const ProcessAnimator: React.FC<ProcessContainerProps> = ({
.filter(([_, obj]) => obj.visible)
.map(([objectId, obj]) => {
const process = processedProcesses.find((p) => p.id === processId);
const renderAs = process?.renderAs || "custom";
return (

View File

@@ -6,18 +6,24 @@ interface ProcessContainerProps {
processes: any[];
setProcesses: React.Dispatch<React.SetStateAction<any[]>>;
agvRef: any;
MaterialRef: any;
}
const ProcessContainer: React.FC<ProcessContainerProps> = ({
processes,
setProcesses,
agvRef
agvRef,
MaterialRef,
}) => {
console.log("processes: ", processes);
return (
<>
<ProcessCreator onProcessesCreated={setProcesses} />
<ProcessAnimator processes={processes} setProcesses={setProcesses} agvRef={agvRef}/>
<ProcessAnimator
processes={processes}
setProcesses={setProcesses}
agvRef={agvRef}
MaterialRef={MaterialRef}
/>
</>
);
};

View File

@@ -25,7 +25,6 @@ interface EnhancedProcessAnimationState extends ProcessAnimationState {
pointId: string;
objectId: string;
triggerId: string;
hasSpawnedZeroIntervalObject?: boolean;
}>;
}
@@ -139,7 +138,6 @@ export const useProcessAnimation = (
processDelayDuration: 0,
triggerCounts,
triggerLogs: [],
hasSpawnedZeroIntervalObject: false, // Initialize the new property
};
});
@@ -453,7 +451,7 @@ export const useProcessAnimation = (
// Increment expectedHitCount if not playing
if (!vehicleEntry.isplaying) {
vehicleEntry.expectedHitCount = processTotalHits + 1;
vehicleEntry.expectedHitCount = processTotalHits;
}
// Set vehicle's hitCount to the processTotalHits

View File

@@ -18,6 +18,7 @@ function Simulation() {
const { simulationStates, setSimulationStates } = useSimulationStates();
const [processes, setProcesses] = useState<any[]>([]);
const agvRef = useRef([]);
const MaterialRef = useRef([]);
return (
<>
@@ -26,8 +27,17 @@ function Simulation() {
<>
<PathCreation pathsGroupRef={pathsGroupRef} />
<PathConnector pathsGroupRef={pathsGroupRef} />
<ProcessContainer processes={processes} setProcesses={setProcesses} agvRef={agvRef} />
<Agv processes={processes} agvRef={agvRef} />
<ProcessContainer
processes={processes}
setProcesses={setProcesses}
agvRef={agvRef}
MaterialRef={MaterialRef}
/>
<Agv
processes={processes}
agvRef={agvRef}
MaterialRef={MaterialRef}
/>
</>
)}
</>

View File

@@ -1,55 +1,22 @@
// import html2canvas from "html2canvas";
export const captureVisualization = async (): Promise<string | null> => {
const container = document.getElementById("real-time-vis-canvas");
if (!container) return null;
const container = document.getElementById("real-time-vis-canvas");
if (!container) return null;
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
if (!ctx) return null;
try {
// Use html2canvas to capture the container
// const canvas = await html2canvas(container, {
// scale: 1, // Adjust scale for higher/lower resolution
// });
const rect = container.getBoundingClientRect();
canvas.width = rect.width;
canvas.height = rect.height;
// // Convert the canvas to a data URL (PNG format)
// const dataUrl = canvas.toDataURL("image/png");
// return dataUrl;
// Draw background
ctx.fillStyle = getComputedStyle(container).backgroundColor;
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Capture all canvas elements
const canvases = container.querySelectorAll("canvas");
canvases.forEach((childCanvas) => {
const childRect = childCanvas.getBoundingClientRect();
const x = childRect.left - rect.left;
const y = childRect.top - rect.top;
ctx.drawImage(childCanvas, x, y, childRect.width, childRect.height);
});
// Capture SVG elements
const svgs = container.querySelectorAll("svg");
for (const svg of Array.from(svgs)) {
const svgString = new XMLSerializer().serializeToString(svg);
const svgBlob = new Blob([svgString], { type: "image/svg+xml" });
const url = URL.createObjectURL(svgBlob);
try {
const img = await new Promise<HTMLImageElement>((resolve, reject) => {
const image = new Image();
image.onload = () => resolve(image);
image.onerror = reject;
image.src = url;
});
const svgRect = svg.getBoundingClientRect();
ctx.drawImage(
img,
svgRect.left - rect.left,
svgRect.top - rect.top,
svgRect.width,
svgRect.height
);
} finally {
URL.revokeObjectURL(url);
}
}
return canvas.toDataURL("image/png");
return null;
} catch (error) {
console.error("Error capturing visualization:", error);
return null;
}
};

View File

@@ -28,10 +28,10 @@ export const handleSaveTemplate = async ({
templates = [],
visualizationSocket,
}: HandleSaveTemplateProps): Promise<void> => {
console.log('floatingWidget: ', floatingWidget);
try {
// Check if the selected zone has any widgets
if (!selectedZone.panelOrder || selectedZone.panelOrder.length === 0) {
console.warn("No widgets found in the selected zone.");
return;
}
@@ -49,7 +49,8 @@ export const handleSaveTemplate = async ({
}
// Capture visualization snapshot
const snapshot = await captureVisualization();
// const snapshot = await captureVisualization();
const snapshot = null;
// if (!snapshot) {
// return;
@@ -72,7 +73,6 @@ export const handleSaveTemplate = async ({
: "";
if (!organization) {
console.error("Organization could not be determined from email.");
return;
}
let saveTemplate = {
@@ -87,13 +87,13 @@ export const handleSaveTemplate = async ({
try {
addTemplate(newTemplate);
// const response = await saveTemplateApi(organization, newTemplate);
// console.log("Save API Response:", response);
//
// Add template only if API call succeeds
} catch (apiError) {
// console.error("Error saving template to API:", apiError);
//
}
} catch (error) {
// console.error("Error in handleSaveTemplate:", error);
//
}
};

View File

@@ -15,22 +15,19 @@ type WidgetData = {
export default function SocketRealTimeViz() {
const { visualizationSocket } = useSocketStore();
const { selectedZone, setSelectedZone } = useSelectedZoneStore();
const { setSelectedZone } = useSelectedZoneStore();
const deleteObject = useDroppedObjectsStore((state) => state.deleteObject);
const duplicateObject = useDroppedObjectsStore((state) => state.duplicateObject);
const updateObjectPosition = useDroppedObjectsStore((state) => state.updateObjectPosition);
const { addWidget } = useZoneWidgetStore()
const { templates, removeTemplate } = useTemplateStore();
const { removeTemplate } = useTemplateStore();
const { setTemplates } = useTemplateStore();
const { zoneWidgetData, setZoneWidgetData, updateWidgetPosition, updateWidgetRotation } = useZoneWidgetStore();
useEffect(() => {
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
if (visualizationSocket) {
//add panel response
visualizationSocket.on("viz-panel:response:updates", (addPanel: any) => {
console.log('addPanel: ', addPanel);
if (addPanel.success) {
let addPanelData = addPanel.data.data
setSelectedZone(addPanelData)
@@ -38,15 +35,33 @@ export default function SocketRealTimeViz() {
})
//delete panel response
visualizationSocket.on("viz-panel:response:delete", (deletePanel: any) => {
console.log('deletePanel: ', deletePanel);
if (deletePanel.success) {
let deletePanelData = deletePanel.data.data
setSelectedZone(deletePanelData)
}
})
//clear Panel response
visualizationSocket.on("viz-panel:response:clear", (clearPanel: any) => {
if (clearPanel.success && clearPanel.message === "PanelWidgets cleared successfully") {
let clearPanelData = clearPanel.data.data
setSelectedZone(clearPanelData)
}
})
//lock Panel response
visualizationSocket.on("viz-panel:response:locked", (lockPanel: any) => {
if (lockPanel.success && lockPanel.message === "locked panel updated successfully") {
let lockPanelData = lockPanel.data.data
setSelectedZone(lockPanelData)
}
})
// add 2dWidget response
visualizationSocket.on("viz-widget:response:updates", (add2dWidget: any) => {
console.log('add2dWidget: ', add2dWidget);
if (add2dWidget.success && add2dWidget.data) {
setSelectedZone((prev) => {
@@ -65,7 +80,7 @@ export default function SocketRealTimeViz() {
});
//delete 2D Widget response
visualizationSocket.on("viz-widget:response:delete", (deleteWidget: any) => {
console.log('deleteWidget: ', deleteWidget);
if (deleteWidget?.success && deleteWidget.data) {
setSelectedZone((prevZone: any) => ({
@@ -78,7 +93,7 @@ export default function SocketRealTimeViz() {
});
//add Floating Widget response
visualizationSocket.on("viz-float:response:updates", (addFloatingWidget: any) => {
console.log('addFloatingWidget: ', addFloatingWidget);
if (addFloatingWidget.success) {
if (addFloatingWidget.success && addFloatingWidget.message === "FloatWidget created successfully") {
@@ -105,7 +120,7 @@ export default function SocketRealTimeViz() {
});
//duplicate Floating Widget response
visualizationSocket.on("viz-float:response:addDuplicate", (duplicateFloatingWidget: any) => {
console.log('duplicateFloatingWidget: ', duplicateFloatingWidget);
if (duplicateFloatingWidget.success && duplicateFloatingWidget.message === "duplicate FloatWidget created successfully") {
useDroppedObjectsStore.setState((state) => {
@@ -133,7 +148,7 @@ export default function SocketRealTimeViz() {
});
//delete Floating Widget response
visualizationSocket.on("viz-float:response:delete", (deleteFloatingWidget: any) => {
console.log('deleteFloatingWidget: ', deleteFloatingWidget);
if (deleteFloatingWidget.success) {
deleteObject(deleteFloatingWidget.data.zoneName, deleteFloatingWidget.data.floatWidgetID);
@@ -142,9 +157,9 @@ export default function SocketRealTimeViz() {
//add 3D Widget response
visualizationSocket.on("viz-widget3D:response:updates", (add3DWidget: any) => {
console.log('add3DWidget: ', add3DWidget);
if (add3DWidget.success) {
console.log('add3DWidget: ', add3DWidget);
if (add3DWidget.message === "Widget created successfully") {
addWidget(add3DWidget.data.zoneId, add3DWidget.data.widget);
}
@@ -152,7 +167,7 @@ export default function SocketRealTimeViz() {
});
//delete 3D Widget response
visualizationSocket.on("viz-widget3D:response:delete", (delete3DWidget: any) => {
console.log('delete3DWidget: ', delete3DWidget);
// "3DWidget delete unsuccessfull"
if (delete3DWidget.success && delete3DWidget.message === "3DWidget delete successfull") {
const activeZoneWidgets = zoneWidgetData[delete3DWidget.data.zoneId] || [];
@@ -164,16 +179,16 @@ export default function SocketRealTimeViz() {
});
//update3D widget response
visualizationSocket.on("viz-widget3D:response:modifyPositionRotation", (update3DWidget: any) => {
console.log('update3DWidget: ', update3DWidget);
if (update3DWidget.success && update3DWidget.message==="widget update successfully") {
if (update3DWidget.success && update3DWidget.message === "widget update successfully") {
updateWidgetPosition(update3DWidget.data.zoneId, update3DWidget.data.widget.id, update3DWidget.data.widget.position);
updateWidgetRotation(update3DWidget.data.zoneId, update3DWidget.data.widget.id, update3DWidget.data.widget.rotation);
}
});
// add Template response
visualizationSocket.on("viz-template:response:add", (addingTemplate: any) => {
console.log('addingTemplate: ', addingTemplate);
if (addingTemplate.success) {
if (addingTemplate.message === "Template saved successfully") {
@@ -183,7 +198,7 @@ export default function SocketRealTimeViz() {
});
//load Template response
visualizationSocket.on("viz-template:response:addTemplateZone", (loadTemplate: any) => {
console.log('loadTemplate: ', loadTemplate);
if (loadTemplate.success) {
if (loadTemplate.message === "Template placed in Zone") {
@@ -206,14 +221,12 @@ export default function SocketRealTimeViz() {
});
//delete Template response
visualizationSocket.on("viz-template:response:delete", (deleteTemplate: any) => {
console.log('deleteTemplate: ', deleteTemplate);
if (deleteTemplate.success) {
if (deleteTemplate.message === 'Template deleted successfully') {
removeTemplate(deleteTemplate.data);
}
}
});
}