remove custom raycasters

This commit is contained in:
wass08
2026-02-09 12:23:38 +09:00
parent 7b999b0952
commit 81f132611e
2 changed files with 273 additions and 539 deletions
@@ -1,13 +1,11 @@
import { emitter, type GridEvent, useScene, CeilingNode, type LevelNode, sceneRegistry } from "@pascal-app/core"; import { emitter, type GridEvent, useScene, CeilingNode } from "@pascal-app/core";
import { useViewer } from "@pascal-app/viewer"; import { useViewer } from "@pascal-app/viewer";
import { useFrame } from "@react-three/fiber";
import { useEffect, useMemo, useRef, useState } from "react"; import { useEffect, useMemo, useRef, useState } from "react";
import { BufferGeometry, DoubleSide, type Line, type Mesh, Plane, Raycaster, Shape, Vector3 } from "three"; import { BufferGeometry, DoubleSide, type Line, type Mesh, Shape, Vector3 } from "three";
import useEditor from "@/store/use-editor"; import useEditor from "@/store/use-editor";
const CEILING_HEIGHT = 2.52; // Slightly above default ceiling height const CEILING_HEIGHT = 2.52;
const GRID_OFFSET = 0.02; // Small offset above floor level const GRID_OFFSET = 0.02;
const UP = new Vector3(0, 1, 0);
/** /**
* Snaps a point to the nearest axis-aligned or 45-degree diagonal from the last point * Snaps a point to the nearest axis-aligned or 45-degree diagonal from the last point
@@ -52,7 +50,7 @@ const calculateSnapPoint = (
* Creates a ceiling with the given polygon points * Creates a ceiling with the given polygon points
*/ */
const commitCeilingDrawing = ( const commitCeilingDrawing = (
levelId: LevelNode["id"], levelId: string,
points: Array<[number, number]> points: Array<[number, number]>
) => { ) => {
const { createNode, nodes } = useScene.getState(); const { createNode, nodes } = useScene.getState();
@@ -69,88 +67,115 @@ const commitCeilingDrawing = (
createNode(ceiling, levelId); createNode(ceiling, levelId);
}; };
type PreviewState = {
points: Array<[number, number]>;
cursorPoint: [number, number] | null;
levelY: number;
};
// Helper to validate point values (no NaN or Infinity)
const isValidPoint = (
pt: [number, number] | null | undefined
): pt is [number, number] => {
if (!pt) return false;
return Number.isFinite(pt[0]) && Number.isFinite(pt[1]);
};
export const CeilingTool: React.FC = () => { export const CeilingTool: React.FC = () => {
const cursorRef = useRef<Mesh>(null); const cursorRef = useRef<Mesh>(null);
const gridCursorRef = useRef<Mesh>(null); const gridCursorRef = useRef<Mesh>(null);
const mainLineRef = useRef<Line>(null!); const mainLineRef = useRef<Line>(null!);
const closingLineRef = useRef<Line>(null!); const closingLineRef = useRef<Line>(null!);
const pointsRef = useRef<Array<[number, number]>>([]);
const levelYRef = useRef(0);
const cursorPositionRef = useRef<[number, number]>([0, 0]);
const lastDisplayRef = useRef<{ x: number; z: number } | null>(null);
const currentLevelId = useViewer((state) => state.selection.levelId); const currentLevelId = useViewer((state) => state.selection.levelId);
const setTool = useEditor((state) => state.setTool); const setTool = useEditor((state) => state.setTool);
// Reusable objects for raycasting (created once, avoid per-frame allocations) const [points, setPoints] = useState<Array<[number, number]>>([]);
const raycaster = useMemo(() => new Raycaster(), []); const [cursorPosition, setCursorPosition] = useState<[number, number]>([0, 0]);
const levelPlane = useMemo(() => new Plane(UP, 0), []); const [levelY, setLevelY] = useState(0);
const hitPoint = useMemo(() => new Vector3(), []);
// Preview state for reactive rendering (for shape and point markers) // Update cursor position and lines on grid move
const [preview, setPreview] = useState<PreviewState>({ useEffect(() => {
points: [], if (!currentLevelId) return;
cursorPoint: null,
levelY: 0,
});
// Resolve the current level's Y position from scene registry or node data const onGridMove = (event: GridEvent) => {
const getLevelY = (): number => { if (!cursorRef.current || !gridCursorRef.current) return;
if (!currentLevelId) return 0;
const levelMesh = sceneRegistry.nodes.get(currentLevelId);
if (levelMesh) return levelMesh.position.y;
const levelNode = useScene.getState().nodes[currentLevelId];
if (levelNode && 'level' in levelNode) {
const levelMode = useViewer.getState().levelMode;
const LEVEL_HEIGHT = 2.5;
const EXPLODED_GAP = 5;
return ((levelNode as any).level || 0) * (LEVEL_HEIGHT + (levelMode === 'exploded' ? EXPLODED_GAP : 0));
}
return 0;
};
// Imperatively update line geometries (called from useFrame) const gridX = Math.round(event.position[0] * 2) / 2;
const updateLines = () => { const gridZ = Math.round(event.position[2] * 2) / 2;
const gridPosition: [number, number] = [gridX, gridZ];
setCursorPosition(gridPosition);
setLevelY(event.position[1]);
const ceilingY = event.position[1] + CEILING_HEIGHT;
const gridY = event.position[1] + GRID_OFFSET;
// Calculate snapped display position
const lastPoint = points[points.length - 1];
const displayPoint = lastPoint
? calculateSnapPoint(lastPoint, gridPosition)
: gridPosition;
cursorRef.current.position.set(displayPoint[0], ceilingY, displayPoint[1]);
gridCursorRef.current.position.set(displayPoint[0], gridY, displayPoint[1]);
};
const onGridClick = (_event: GridEvent) => {
if (!currentLevelId) return;
// Calculate snapped click point
const lastPoint = points[points.length - 1];
const clickPoint = lastPoint
? calculateSnapPoint(lastPoint, cursorPosition)
: cursorPosition;
// Check if clicking on the first point to close the shape
const firstPoint = points[0];
if (
points.length >= 3 &&
firstPoint &&
Math.abs(clickPoint[0] - firstPoint[0]) < 0.25 &&
Math.abs(clickPoint[1] - firstPoint[1]) < 0.25
) {
// Create the ceiling
commitCeilingDrawing(currentLevelId, points);
setPoints([]);
setTool(null);
} else {
// Add point to polygon
setPoints([...points, clickPoint]);
}
};
const onGridDoubleClick = (_event: GridEvent) => {
if (!currentLevelId) return;
// Need at least 3 points to form a polygon
if (points.length >= 3) {
commitCeilingDrawing(currentLevelId, points);
setPoints([]);
setTool(null);
}
};
emitter.on("grid:move", onGridMove);
emitter.on("grid:click", onGridClick);
emitter.on("grid:double-click", onGridDoubleClick);
return () => {
emitter.off("grid:move", onGridMove);
emitter.off("grid:click", onGridClick);
emitter.off("grid:double-click", onGridDoubleClick);
};
}, [currentLevelId, points, cursorPosition, setTool]);
// Update line geometries when points change
useEffect(() => {
if (!mainLineRef.current || !closingLineRef.current) return; if (!mainLineRef.current || !closingLineRef.current) return;
const points = pointsRef.current;
const cursorPosition = cursorPositionRef.current;
const ceilingY = levelYRef.current + CEILING_HEIGHT;
if (points.length === 0) { if (points.length === 0) {
mainLineRef.current.visible = false; mainLineRef.current.visible = false;
closingLineRef.current.visible = false; closingLineRef.current.visible = false;
return; return;
} }
// Build main line points const ceilingY = levelY + CEILING_HEIGHT;
const linePoints: Vector3[] = points.map(
([x, z]) => new Vector3(x, ceilingY, z)
);
// Add cursor point
const lastPoint = points[points.length - 1]; const lastPoint = points[points.length - 1];
if (lastPoint) { const snappedCursor = lastPoint
const snapped = calculateSnapPoint(lastPoint, cursorPosition); ? calculateSnapPoint(lastPoint, cursorPosition)
if (isValidPoint(snapped)) { : cursorPosition;
linePoints.push(new Vector3(snapped[0], ceilingY, snapped[1]));
}
}
// Update main line geometry // Build main line points
const linePoints: Vector3[] = points.map(([x, z]) => new Vector3(x, ceilingY, z));
linePoints.push(new Vector3(snappedCursor[0], ceilingY, snappedCursor[1]));
// Update main line
if (linePoints.length >= 2) { if (linePoints.length >= 2) {
mainLineRef.current.geometry.dispose(); mainLineRef.current.geometry.dispose();
mainLineRef.current.geometry = new BufferGeometry().setFromPoints(linePoints); mainLineRef.current.geometry = new BufferGeometry().setFromPoints(linePoints);
@@ -161,195 +186,49 @@ export const CeilingTool: React.FC = () => {
// Update closing line (from cursor back to first point) // Update closing line (from cursor back to first point)
const firstPoint = points[0]; const firstPoint = points[0];
if (points.length >= 2 && lastPoint && isValidPoint(firstPoint)) { if (points.length >= 2 && firstPoint) {
const snapped = calculateSnapPoint(lastPoint, cursorPosition); const closingPoints = [
if (isValidPoint(snapped)) { new Vector3(snappedCursor[0], ceilingY, snappedCursor[1]),
const closingPoints = [ new Vector3(firstPoint[0], ceilingY, firstPoint[1]),
new Vector3(snapped[0], ceilingY, snapped[1]), ];
new Vector3(firstPoint[0], ceilingY, firstPoint[1]), closingLineRef.current.geometry.dispose();
]; closingLineRef.current.geometry = new BufferGeometry().setFromPoints(closingPoints);
closingLineRef.current.geometry.dispose(); closingLineRef.current.visible = true;
closingLineRef.current.geometry = new BufferGeometry().setFromPoints(closingPoints);
closingLineRef.current.visible = true;
}
} else { } else {
closingLineRef.current.visible = false; closingLineRef.current.visible = false;
} }
}; }, [points, cursorPosition, levelY]);
// Per-frame cursor positioning via direct raycasting onto the level plane.
// This bypasses R3F's event propagation (grid:move), ensuring the cursor
// always tracks the pointer regardless of tool activation/deactivation state.
useFrame((state) => {
if (!cursorRef.current) return;
// Sync level Y from scene registry each frame
levelYRef.current = getLevelY();
// Raycast from camera through pointer onto horizontal plane at level Y
raycaster.setFromCamera(state.pointer, state.camera);
levelPlane.constant = -levelYRef.current;
const hit = raycaster.ray.intersectPlane(levelPlane, hitPoint);
if (!hit) return;
// Snap to 0.5m grid
const gridX = Math.round(hit.x * 2) / 2;
const gridZ = Math.round(hit.z * 2) / 2;
cursorPositionRef.current = [gridX, gridZ];
const ceilingY = levelYRef.current + CEILING_HEIGHT;
const gridY = levelYRef.current + GRID_OFFSET;
// Apply axis snapping from last placed point
const lastPoint = pointsRef.current[pointsRef.current.length - 1];
let displayPoint: [number, number];
if (lastPoint) {
displayPoint = calculateSnapPoint(lastPoint, cursorPositionRef.current);
} else {
displayPoint = [gridX, gridZ];
}
// Update cursor mesh positions imperatively
cursorRef.current.position.set(displayPoint[0], ceilingY, displayPoint[1]);
if (gridCursorRef.current) {
gridCursorRef.current.position.set(displayPoint[0], gridY, displayPoint[1]);
}
// Update line geometries imperatively
updateLines();
// Only trigger React state update when snapped display position changes
if (
!lastDisplayRef.current ||
lastDisplayRef.current.x !== displayPoint[0] ||
lastDisplayRef.current.z !== displayPoint[1]
) {
lastDisplayRef.current = { x: displayPoint[0], z: displayPoint[1] };
setPreview({
points: [...pointsRef.current],
cursorPoint: displayPoint,
levelY: levelYRef.current,
});
}
});
// Click and double-click handlers for point placement
useEffect(() => {
if (!currentLevelId) return;
// Initialize line geometries
if (mainLineRef.current) {
mainLineRef.current.geometry = new BufferGeometry();
}
if (closingLineRef.current) {
closingLineRef.current.geometry = new BufferGeometry();
}
// Reset state on level change
pointsRef.current = [];
lastDisplayRef.current = null;
setPreview({ points: [], cursorPoint: null, levelY: getLevelY() });
const onGridClick = (_event: GridEvent) => {
if (!currentLevelId) return;
// Use the cursor position tracked by useFrame (matches what user sees)
let clickPoint: [number, number] = [...cursorPositionRef.current];
// Snap to axis from last point
const lastPoint = pointsRef.current[pointsRef.current.length - 1];
if (lastPoint) {
clickPoint = calculateSnapPoint(lastPoint, clickPoint);
}
// Check if clicking on the first point to close the shape
const firstPoint = pointsRef.current[0];
if (
pointsRef.current.length >= 3 &&
firstPoint &&
Math.abs(clickPoint[0] - firstPoint[0]) < 0.25 &&
Math.abs(clickPoint[1] - firstPoint[1]) < 0.25
) {
// Create the ceiling
commitCeilingDrawing(currentLevelId, pointsRef.current);
// Reset state
pointsRef.current = [];
lastDisplayRef.current = null;
setPreview({ points: [], cursorPoint: null, levelY: levelYRef.current });
if (mainLineRef.current) mainLineRef.current.visible = false;
if (closingLineRef.current) closingLineRef.current.visible = false;
// Deactivate tool
setTool(null);
} else {
// Add point to polygon
pointsRef.current = [...pointsRef.current, clickPoint];
lastDisplayRef.current = null; // Force preview update on next frame
}
};
const onGridDoubleClick = (_event: GridEvent) => {
if (!currentLevelId) return;
// Need at least 3 points to form a polygon
if (pointsRef.current.length >= 3) {
commitCeilingDrawing(currentLevelId, pointsRef.current);
// Reset state
pointsRef.current = [];
lastDisplayRef.current = null;
setPreview({ points: [], cursorPoint: null, levelY: levelYRef.current });
if (mainLineRef.current) mainLineRef.current.visible = false;
if (closingLineRef.current) closingLineRef.current.visible = false;
// Deactivate tool
setTool(null);
}
};
emitter.on("grid:click", onGridClick);
emitter.on("grid:double-click", onGridDoubleClick);
return () => {
emitter.off("grid:click", onGridClick);
emitter.off("grid:double-click", onGridDoubleClick);
// Reset state on unmount
pointsRef.current = [];
};
}, [currentLevelId, setTool]);
const { points, cursorPoint, levelY } = preview;
// Create preview shape when we have 3+ points // Create preview shape when we have 3+ points
const previewShape = useMemo(() => { const previewShape = useMemo(() => {
if (points.length < 3) return null; if (points.length < 3) return null;
const allPoints = [...points]; const lastPoint = points[points.length - 1];
if (isValidPoint(cursorPoint)) { const snappedCursor = lastPoint
allPoints.push(cursorPoint); ? calculateSnapPoint(lastPoint, cursorPosition)
} : cursorPosition;
const allPoints = [...points, snappedCursor];
// THREE.Shape is in X-Y plane. After rotation of -PI/2 around X: // THREE.Shape is in X-Y plane. After rotation of -PI/2 around X:
// - Shape X -> World X // - Shape X -> World X
// - Shape Y -> World -Z (so we negate Z to get correct orientation) // - Shape Y -> World -Z (so we negate Z to get correct orientation)
const firstPt = allPoints[0]; const firstPt = allPoints[0];
if (!isValidPoint(firstPt)) return null; if (!firstPt) return null;
const shape = new Shape(); const shape = new Shape();
shape.moveTo(firstPt[0], -firstPt[1]); shape.moveTo(firstPt[0], -firstPt[1]);
for (let i = 1; i < allPoints.length; i++) { for (let i = 1; i < allPoints.length; i++) {
const pt = allPoints[i]; const pt = allPoints[i];
if (isValidPoint(pt)) { if (pt) {
shape.lineTo(pt[0], -pt[1]); shape.lineTo(pt[0], -pt[1]);
} }
} }
shape.closePath(); shape.closePath();
return shape; return shape;
}, [points, cursorPoint]); }, [points, cursorPosition]);
return ( return (
<group> <group>
@@ -392,7 +271,7 @@ export const CeilingTool: React.FC = () => {
</mesh> </mesh>
)} )}
{/* Main line - uses native line element with TSL-compatible material */} {/* Main line */}
{/* @ts-ignore */} {/* @ts-ignore */}
<line ref={mainLineRef} frustumCulled={false} renderOrder={1} visible={false}> <line ref={mainLineRef} frustumCulled={false} renderOrder={1} visible={false}>
<bufferGeometry /> <bufferGeometry />
@@ -404,7 +283,7 @@ export const CeilingTool: React.FC = () => {
/> />
</line> </line>
{/* Closing line - uses native line element with TSL-compatible material */} {/* Closing line */}
{/* @ts-ignore */} {/* @ts-ignore */}
<line ref={closingLineRef} frustumCulled={false} renderOrder={1} visible={false}> <line ref={closingLineRef} frustumCulled={false} renderOrder={1} visible={false}>
<bufferGeometry /> <bufferGeometry />
@@ -419,18 +298,16 @@ export const CeilingTool: React.FC = () => {
</line> </line>
{/* Point markers */} {/* Point markers */}
{points.map(([x, z], index) => {points.map(([x, z], index) => (
isValidPoint([x, z]) ? ( <mesh key={index} position={[x, levelY + CEILING_HEIGHT + 0.01, z]}>
<mesh key={index} position={[x, levelY + CEILING_HEIGHT + 0.01, z]}> <sphereGeometry args={[0.1, 16, 16]} />
<sphereGeometry args={[0.1, 16, 16]} /> <meshBasicMaterial
<meshBasicMaterial color={index === 0 ? "#22c55e" : "#d4d4d4"}
color={index === 0 ? "#22c55e" : "#d4d4d4"} depthTest={false}
depthTest={false} depthWrite={false}
depthWrite={false} />
/> </mesh>
</mesh> ))}
) : null
)}
</group> </group>
); );
}; };
+150 -293
View File
@@ -1,357 +1,221 @@
import { emitter, type GridEvent, useScene, SlabNode, type LevelNode, sceneRegistry } from "@pascal-app/core"; import { emitter, type GridEvent, type LevelNode, SlabNode, useScene } from '@pascal-app/core'
import { useViewer } from "@pascal-app/viewer"; import { useViewer } from '@pascal-app/viewer'
import { useFrame } from "@react-three/fiber"; import { useEffect, useMemo, useRef, useState } from 'react'
import { useEffect, useMemo, useRef, useState } from "react"; import { BufferGeometry, DoubleSide, type Line, type Mesh, Shape, Vector3 } from 'three'
import { BufferGeometry, DoubleSide, type Line, type Mesh, Plane, Raycaster, Shape, Vector3 } from "three";
import useEditor from "@/store/use-editor";
const Y_OFFSET = 0.02; // Small offset above floor level const Y_OFFSET = 0.02
const UP = new Vector3(0, 1, 0);
/** /**
* Snaps a point to the nearest axis-aligned or 45-degree diagonal from the last point * Snaps a point to the nearest axis-aligned or 45-degree diagonal from the last point
*/ */
const calculateSnapPoint = ( const calculateSnapPoint = (
lastPoint: [number, number], lastPoint: [number, number],
currentPoint: [number, number] currentPoint: [number, number],
): [number, number] => { ): [number, number] => {
const [x1, y1] = lastPoint; const [x1, y1] = lastPoint
const [x, y] = currentPoint; const [x, y] = currentPoint
const dx = x - x1; const dx = x - x1
const dy = y - y1; const dy = y - y1
const absDx = Math.abs(dx); const absDx = Math.abs(dx)
const absDy = Math.abs(dy); const absDy = Math.abs(dy)
// Calculate distances to horizontal, vertical, and diagonal lines // Calculate distances to horizontal, vertical, and diagonal lines
const horizontalDist = absDy; const horizontalDist = absDy
const verticalDist = absDx; const verticalDist = absDx
const diagonalDist = Math.abs(absDx - absDy); const diagonalDist = Math.abs(absDx - absDy)
// Find the minimum distance to determine which axis to snap to // Find the minimum distance to determine which axis to snap to
const minDist = Math.min(horizontalDist, verticalDist, diagonalDist); const minDist = Math.min(horizontalDist, verticalDist, diagonalDist)
if (minDist === diagonalDist) { if (minDist === diagonalDist) {
// Snap to 45° diagonal // Snap to 45° diagonal
const diagonalLength = Math.min(absDx, absDy); const diagonalLength = Math.min(absDx, absDy)
return [ return [x1 + Math.sign(dx) * diagonalLength, y1 + Math.sign(dy) * diagonalLength]
x1 + Math.sign(dx) * diagonalLength,
y1 + Math.sign(dy) * diagonalLength,
];
} else if (minDist === horizontalDist) { } else if (minDist === horizontalDist) {
// Snap to horizontal // Snap to horizontal
return [x, y1]; return [x, y1]
} else { } else {
// Snap to vertical // Snap to vertical
return [x1, y]; return [x1, y]
} }
}; }
/** /**
* Creates a slab with the given polygon points and returns its ID * Creates a slab with the given polygon points and returns its ID
*/ */
const commitSlabDrawing = ( const commitSlabDrawing = (levelId: LevelNode['id'], points: Array<[number, number]>): string => {
levelId: LevelNode["id"], const { createNode, nodes } = useScene.getState()
points: Array<[number, number]>
): string => {
const { createNode, nodes } = useScene.getState();
// Count existing slabs for naming // Count existing slabs for naming
const slabCount = Object.values(nodes).filter((n) => n.type === "slab").length; const slabCount = Object.values(nodes).filter((n) => n.type === 'slab').length
const name = `Slab ${slabCount + 1}`; const name = `Slab ${slabCount + 1}`
const slab = SlabNode.parse({ const slab = SlabNode.parse({
name, name,
polygon: points, polygon: points,
}); })
createNode(slab, levelId); createNode(slab, levelId)
return slab.id; return slab.id
}; }
type PreviewState = {
points: Array<[number, number]>;
cursorPoint: [number, number] | null;
levelY: number;
};
// Helper to validate point values (no NaN or Infinity)
const isValidPoint = (
pt: [number, number] | null | undefined
): pt is [number, number] => {
if (!pt) return false;
return Number.isFinite(pt[0]) && Number.isFinite(pt[1]);
};
export const SlabTool: React.FC = () => { export const SlabTool: React.FC = () => {
const cursorRef = useRef<Mesh>(null); const cursorRef = useRef<Mesh>(null)
const mainLineRef = useRef<Line>(null!); const mainLineRef = useRef<Line>(null!)
const closingLineRef = useRef<Line>(null!); const closingLineRef = useRef<Line>(null!)
const pointsRef = useRef<Array<[number, number]>>([]); const currentLevelId = useViewer((state) => state.selection.levelId)
const levelYRef = useRef(0); const setSelection = useViewer((state) => state.setSelection)
const cursorPositionRef = useRef<[number, number]>([0, 0]);
const lastDisplayRef = useRef<{ x: number; z: number } | null>(null);
const currentLevelId = useViewer((state) => state.selection.levelId);
const setSelection = useViewer((state) => state.setSelection);
const setTool = useEditor((state) => state.setTool);
// Reusable objects for raycasting (created once, avoid per-frame allocations) const [points, setPoints] = useState<Array<[number, number]>>([])
const raycaster = useMemo(() => new Raycaster(), []); const [cursorPosition, setCursorPosition] = useState<[number, number]>([0, 0])
const levelPlane = useMemo(() => new Plane(UP, 0), []); const [levelY, setLevelY] = useState(0)
const hitPoint = useMemo(() => new Vector3(), []);
// Preview state for reactive rendering (for shape and point markers) // Update cursor position and lines on grid move
const [preview, setPreview] = useState<PreviewState>({
points: [],
cursorPoint: null,
levelY: 0,
});
// Resolve the current level's Y position from scene registry or node data
const getLevelY = (): number => {
if (!currentLevelId) return 0;
const levelMesh = sceneRegistry.nodes.get(currentLevelId);
if (levelMesh) return levelMesh.position.y;
const levelNode = useScene.getState().nodes[currentLevelId];
if (levelNode && 'level' in levelNode) {
const levelMode = useViewer.getState().levelMode;
const LEVEL_HEIGHT = 2.5;
const EXPLODED_GAP = 5;
return ((levelNode as any).level || 0) * (LEVEL_HEIGHT + (levelMode === 'exploded' ? EXPLODED_GAP : 0));
}
return 0;
};
// Imperatively update line geometries (called from useFrame)
const updateLines = () => {
if (!mainLineRef.current || !closingLineRef.current) return;
const points = pointsRef.current;
const cursorPosition = cursorPositionRef.current;
const y = levelYRef.current + Y_OFFSET;
if (points.length === 0) {
mainLineRef.current.visible = false;
closingLineRef.current.visible = false;
return;
}
// Build main line points
const linePoints: Vector3[] = points.map(
([x, z]) => new Vector3(x, y, z)
);
// Add cursor point
const lastPoint = points[points.length - 1];
if (lastPoint) {
const snapped = calculateSnapPoint(lastPoint, cursorPosition);
if (isValidPoint(snapped)) {
linePoints.push(new Vector3(snapped[0], y, snapped[1]));
}
}
// Update main line geometry
if (linePoints.length >= 2) {
mainLineRef.current.geometry.dispose();
mainLineRef.current.geometry = new BufferGeometry().setFromPoints(linePoints);
mainLineRef.current.visible = true;
} else {
mainLineRef.current.visible = false;
}
// Update closing line (from cursor back to first point)
const firstPoint = points[0];
if (points.length >= 2 && lastPoint && isValidPoint(firstPoint)) {
const snapped = calculateSnapPoint(lastPoint, cursorPosition);
if (isValidPoint(snapped)) {
const closingPoints = [
new Vector3(snapped[0], y, snapped[1]),
new Vector3(firstPoint[0], y, firstPoint[1]),
];
closingLineRef.current.geometry.dispose();
closingLineRef.current.geometry = new BufferGeometry().setFromPoints(closingPoints);
closingLineRef.current.visible = true;
}
} else {
closingLineRef.current.visible = false;
}
};
// Per-frame cursor positioning via direct raycasting onto the level plane.
// This bypasses R3F's event propagation (grid:move), ensuring the cursor
// always tracks the pointer regardless of tool activation/deactivation state.
useFrame((state) => {
if (!cursorRef.current) return;
// Sync level Y from scene registry each frame
levelYRef.current = getLevelY();
// Raycast from camera through pointer onto horizontal plane at level Y
raycaster.setFromCamera(state.pointer, state.camera);
levelPlane.constant = -levelYRef.current;
const hit = raycaster.ray.intersectPlane(levelPlane, hitPoint);
if (!hit) return;
// Snap to 0.5m grid
const gridX = Math.round(hit.x * 2) / 2;
const gridZ = Math.round(hit.z * 2) / 2;
cursorPositionRef.current = [gridX, gridZ];
// Apply axis snapping from last placed point
const lastPoint = pointsRef.current[pointsRef.current.length - 1];
let displayPoint: [number, number];
if (lastPoint) {
displayPoint = calculateSnapPoint(lastPoint, cursorPositionRef.current);
} else {
displayPoint = [gridX, gridZ];
}
// Update cursor mesh position imperatively
cursorRef.current.position.set(displayPoint[0], levelYRef.current, displayPoint[1]);
// Update line geometries imperatively
updateLines();
// Only trigger React state update when snapped display position changes
if (
!lastDisplayRef.current ||
lastDisplayRef.current.x !== displayPoint[0] ||
lastDisplayRef.current.z !== displayPoint[1]
) {
lastDisplayRef.current = { x: displayPoint[0], z: displayPoint[1] };
setPreview({
points: [...pointsRef.current],
cursorPoint: displayPoint,
levelY: levelYRef.current,
});
}
});
// Click and double-click handlers for point placement
useEffect(() => { useEffect(() => {
if (!currentLevelId) return; if (!currentLevelId) return
// Initialize line geometries const onGridMove = (event: GridEvent) => {
if (mainLineRef.current) { if (!cursorRef.current) return
mainLineRef.current.geometry = new BufferGeometry();
}
if (closingLineRef.current) {
closingLineRef.current.geometry = new BufferGeometry();
}
// Reset state on level change const gridX = Math.round(event.position[0] * 2) / 2
pointsRef.current = []; const gridZ = Math.round(event.position[2] * 2) / 2
lastDisplayRef.current = null; const gridPosition: [number, number] = [gridX, gridZ]
setPreview({ points: [], cursorPoint: null, levelY: getLevelY() });
setCursorPosition(gridPosition)
setLevelY(event.position[1])
// Calculate snapped display position
const lastPoint = points[points.length - 1]
const displayPoint = lastPoint ? calculateSnapPoint(lastPoint, gridPosition) : gridPosition
cursorRef.current.position.set(displayPoint[0], event.position[1], displayPoint[1])
}
const onGridClick = (_event: GridEvent) => { const onGridClick = (_event: GridEvent) => {
if (!currentLevelId) return; if (!currentLevelId) return
// Use the cursor position tracked by useFrame (matches what user sees) // Calculate snapped click point
let clickPoint: [number, number] = [...cursorPositionRef.current]; const lastPoint = points[points.length - 1]
const clickPoint = lastPoint ? calculateSnapPoint(lastPoint, cursorPosition) : cursorPosition
// Snap to axis from last point
const lastPoint = pointsRef.current[pointsRef.current.length - 1];
if (lastPoint) {
clickPoint = calculateSnapPoint(lastPoint, clickPoint);
}
// Check if clicking on the first point to close the shape // Check if clicking on the first point to close the shape
const firstPoint = pointsRef.current[0]; const firstPoint = points[0]
if ( if (
pointsRef.current.length >= 3 && points.length >= 3 &&
firstPoint && firstPoint &&
Math.abs(clickPoint[0] - firstPoint[0]) < 0.25 && Math.abs(clickPoint[0] - firstPoint[0]) < 0.25 &&
Math.abs(clickPoint[1] - firstPoint[1]) < 0.25 Math.abs(clickPoint[1] - firstPoint[1]) < 0.25
) { ) {
// Create the slab and select it // Create the slab and select it
const slabId = commitSlabDrawing(currentLevelId, pointsRef.current); const slabId = commitSlabDrawing(currentLevelId, points)
setSelection({ selectedIds: [slabId] }); setSelection({ selectedIds: [slabId] })
setPoints([])
// Reset state
pointsRef.current = [];
lastDisplayRef.current = null;
setPreview({ points: [], cursorPoint: null, levelY: levelYRef.current });
if (mainLineRef.current) mainLineRef.current.visible = false;
if (closingLineRef.current) closingLineRef.current.visible = false;
} else { } else {
// Add point to polygon // Add point to polygon
pointsRef.current = [...pointsRef.current, clickPoint]; setPoints([...points, clickPoint])
lastDisplayRef.current = null; // Force preview update on next frame
} }
}; }
const onGridDoubleClick = (_event: GridEvent) => { const onGridDoubleClick = (_event: GridEvent) => {
if (!currentLevelId) return; if (!currentLevelId) return
// Need at least 3 points to form a polygon // Need at least 3 points to form a polygon
if (pointsRef.current.length >= 3) { if (points.length >= 3) {
// Create the slab and select it const slabId = commitSlabDrawing(currentLevelId, points)
const slabId = commitSlabDrawing(currentLevelId, pointsRef.current); setSelection({ selectedIds: [slabId] })
setSelection({ selectedIds: [slabId] }); setPoints([])
// Reset state
pointsRef.current = [];
lastDisplayRef.current = null;
setPreview({ points: [], cursorPoint: null, levelY: levelYRef.current });
if (mainLineRef.current) mainLineRef.current.visible = false;
if (closingLineRef.current) closingLineRef.current.visible = false;
} }
}; }
emitter.on("grid:click", onGridClick); emitter.on('grid:move', onGridMove)
emitter.on("grid:double-click", onGridDoubleClick); emitter.on('grid:click', onGridClick)
emitter.on('grid:double-click', onGridDoubleClick)
return () => { return () => {
emitter.off("grid:click", onGridClick); emitter.off('grid:move', onGridMove)
emitter.off("grid:double-click", onGridDoubleClick); emitter.off('grid:click', onGridClick)
emitter.off('grid:double-click', onGridDoubleClick)
}
}, [currentLevelId, points, cursorPosition, setSelection])
// Reset state on unmount // Update line geometries when points change
pointsRef.current = []; useEffect(() => {
}; if (!mainLineRef.current || !closingLineRef.current) return
}, [currentLevelId, setSelection]);
const { points, cursorPoint, levelY } = preview; if (points.length === 0) {
mainLineRef.current.visible = false
closingLineRef.current.visible = false
return
}
const y = levelY + Y_OFFSET
const lastPoint = points[points.length - 1]
const snappedCursor = lastPoint ? calculateSnapPoint(lastPoint, cursorPosition) : cursorPosition
// Build main line points
const linePoints: Vector3[] = points.map(([x, z]) => new Vector3(x, y, z))
linePoints.push(new Vector3(snappedCursor[0], y, snappedCursor[1]))
// Update main line
if (linePoints.length >= 2) {
mainLineRef.current.geometry.dispose()
mainLineRef.current.geometry = new BufferGeometry().setFromPoints(linePoints)
mainLineRef.current.visible = true
} else {
mainLineRef.current.visible = false
}
// Update closing line (from cursor back to first point)
const firstPoint = points[0]
if (points.length >= 2 && firstPoint) {
const closingPoints = [
new Vector3(snappedCursor[0], y, snappedCursor[1]),
new Vector3(firstPoint[0], y, firstPoint[1]),
]
closingLineRef.current.geometry.dispose()
closingLineRef.current.geometry = new BufferGeometry().setFromPoints(closingPoints)
closingLineRef.current.visible = true
} else {
closingLineRef.current.visible = false
}
}, [points, cursorPosition, levelY])
// Create preview shape when we have 3+ points // Create preview shape when we have 3+ points
const previewShape = useMemo(() => { const previewShape = useMemo(() => {
if (points.length < 3) return null; if (points.length < 3) return null
const allPoints = [...points]; const lastPoint = points[points.length - 1]
if (isValidPoint(cursorPoint)) { const snappedCursor = lastPoint ? calculateSnapPoint(lastPoint, cursorPosition) : cursorPosition
allPoints.push(cursorPoint);
} const allPoints = [...points, snappedCursor]
// THREE.Shape is in X-Y plane. After rotation of -PI/2 around X: // THREE.Shape is in X-Y plane. After rotation of -PI/2 around X:
// - Shape X -> World X // - Shape X -> World X
// - Shape Y -> World -Z (so we negate Z to get correct orientation) // - Shape Y -> World -Z (so we negate Z to get correct orientation)
const firstPt = allPoints[0]; const firstPt = allPoints[0]
if (!isValidPoint(firstPt)) return null; if (!firstPt) return null
const shape = new Shape(); const shape = new Shape()
shape.moveTo(firstPt[0], -firstPt[1]); shape.moveTo(firstPt[0], -firstPt[1])
for (let i = 1; i < allPoints.length; i++) { for (let i = 1; i < allPoints.length; i++) {
const pt = allPoints[i]; const pt = allPoints[i]
if (isValidPoint(pt)) { if (pt) {
shape.lineTo(pt[0], -pt[1]); shape.lineTo(pt[0], -pt[1])
} }
} }
shape.closePath(); shape.closePath()
return shape; return shape
}, [points, cursorPoint]); }, [points, cursorPosition])
return ( return (
<group> <group>
{/* Cursor */} {/* Cursor */}
<mesh ref={cursorRef}> <mesh ref={cursorRef}>
<sphereGeometry args={[0.1, 16, 16]} /> <sphereGeometry args={[0.1, 16, 16]} />
<meshBasicMaterial <meshBasicMaterial color="#a3a3a3" depthTest={false} depthWrite={false} />
color="#a3a3a3"
depthTest={false}
depthWrite={false}
/>
</mesh> </mesh>
{/* Preview fill */} {/* Preview fill */}
@@ -372,19 +236,14 @@ export const SlabTool: React.FC = () => {
</mesh> </mesh>
)} )}
{/* Main line - uses native line element with TSL-compatible material */} {/* Main line */}
{/* @ts-ignore */} {/* @ts-ignore */}
<line ref={mainLineRef} frustumCulled={false} renderOrder={1} visible={false}> <line ref={mainLineRef} frustumCulled={false} renderOrder={1} visible={false}>
<bufferGeometry /> <bufferGeometry />
<lineBasicNodeMaterial <lineBasicNodeMaterial color="#737373" linewidth={3} depthTest={false} depthWrite={false} />
color="#737373"
linewidth={3}
depthTest={false}
depthWrite={false}
/>
</line> </line>
{/* Closing line - uses native line element with TSL-compatible material */} {/* Closing line */}
{/* @ts-ignore */} {/* @ts-ignore */}
<line ref={closingLineRef} frustumCulled={false} renderOrder={1} visible={false}> <line ref={closingLineRef} frustumCulled={false} renderOrder={1} visible={false}>
<bufferGeometry /> <bufferGeometry />
@@ -399,18 +258,16 @@ export const SlabTool: React.FC = () => {
</line> </line>
{/* Point markers */} {/* Point markers */}
{points.map(([x, z], index) => {points.map(([x, z], index) => (
isValidPoint([x, z]) ? ( <mesh key={index} position={[x, levelY + Y_OFFSET + 0.01, z]}>
<mesh key={index} position={[x, levelY + Y_OFFSET + 0.01, z]}> <sphereGeometry args={[0.1, 16, 16]} />
<sphereGeometry args={[0.1, 16, 16]} /> <meshBasicMaterial
<meshBasicMaterial color={index === 0 ? '#22c55e' : '#a3a3a3'}
color={index === 0 ? "#22c55e" : "#a3a3a3"} depthTest={false}
depthTest={false} depthWrite={false}
depthWrite={false} />
/> </mesh>
</mesh> ))}
) : null
)}
</group> </group>
); )
}; }