import React from 'react';
import { useThree } from '@react-three/fiber';
import { Line, OrbitControls } from '@react-three/drei';
import * as THREE from 'three';
const DxfContent = ({ data, color = 'black' }) => {
const { scene } = useThree();
const { translationOffset, adjustedCenter, maxDim } = React.useMemo(() => {
const boundingBox = new THREE.Box3();
data.polylines.forEach(polyline => {
polyline.forEach(point => {
boundingBox.expandByPoint(new THREE.Vector3(point[0], point[1], point[2]));
});
});
const zMin = boundingBox.min.z;
const translationOffset = new THREE.Vector3(0, 0, -zMin);
const originalCenter = boundingBox.getCenter(new THREE.Vector3());
const adjustedCenter = originalCenter.clone().add(translationOffset);
const size = boundingBox.getSize(new THREE.Vector3());
const maxDim = Math.max(size.x, size.y, size.z);
return { translationOffset, adjustedCenter, maxDim };
}, [data]);
// Add GridHelper from THREE directly, positioned at the new center
React.useEffect(() => {
const gridHelper = new THREE.GridHelper(maxDim * 2, 20, 0x000000, 0xcccccc);
// The grid itself stays at y=0, but we can align its x/z center with the object
gridHelper.position.set(adjustedCenter.x, 0, adjustedCenter.z);
scene.add(gridHelper);
return () => {
scene.remove(gridHelper);
gridHelper.dispose();
};
}, [maxDim, adjustedCenter, scene]);
return (
<>
<ambientLight intensity={1} />
<pointLight position={[adjustedCenter.x + maxDim, adjustedCenter.y + maxDim, adjustedCenter.z + maxDim]} intensity={0.5} />
<pointLight position={[adjustedCenter.x - maxDim, adjustedCenter.y - maxDim, adjustedCenter.z - maxDim]} intensity={0.5} />
{data.polylines.map((polyline, i) => {
// Apply the translation to each point and explicitly close the loop
const adjustedPoints = polyline.map(p => new THREE.Vector3(p[0], p[1], p[2]).add(translationOffset));
const closedPolyline = [...adjustedPoints, adjustedPoints[0]];
return (
<Line
key={i}
points={closedPolyline}
color={color}
lineWidth={4}
/>
);
})}
<OrbitControls
target={adjustedCenter} // Focus camera on the new, adjusted center
enableDamping
dampingFactor={0.1}
rotateSpeed={0.5}
/>
</>
);
};
export default DxfContent;