diff --git a/README.md b/README.md index dbe131c..b66366a 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,7 @@ | Date | Description | | --- | --- | +| **2026-04-21** | Added Graph Node "Image Compare"
Improved a bit the "Mesh Editor" (not good yet) | | **2026-04-19** | Improve the way to import ComfyUI workflows
Added a draft version of Mesh Editor
Added Change Log in Projects page | | **2026-04-19** | First release | diff --git a/index.html b/index.html index 92008ea..1b17811 100644 --- a/index.html +++ b/index.html @@ -2,7 +2,7 @@ - + 3D Gen Studio diff --git a/package-lock.json b/package-lock.json index 0feb57e..0bd3250 100644 --- a/package-lock.json +++ b/package-lock.json @@ -23,7 +23,8 @@ "react-dom": "^19.2.4", "react-router-dom": "^7.14.0", "sqlite3": "^6.0.1", - "three": "^0.183.2" + "three": "^0.183.2", + "three-mesh-bvh": "^0.9.9" }, "devDependencies": { "@eslint/js": "^9.39.4", @@ -757,6 +758,15 @@ } } }, + "node_modules/@react-three/drei/node_modules/three-mesh-bvh": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/three-mesh-bvh/-/three-mesh-bvh-0.8.3.tgz", + "integrity": "sha512-4G5lBaF+g2auKX3P0yqx+MJC6oVt6sB5k+CchS6Ob0qvH0YIhuUk1eYr7ktsIpY+albCqE80/FVQGV190PmiAg==", + "license": "MIT", + "peerDependencies": { + "three": ">= 0.159.0" + } + }, "node_modules/@react-three/fiber": { "version": "9.5.0", "resolved": "https://registry.npmjs.org/@react-three/fiber/-/fiber-9.5.0.tgz", @@ -5248,9 +5258,9 @@ "license": "MIT" }, "node_modules/three-mesh-bvh": { - "version": "0.8.3", - "resolved": "https://registry.npmjs.org/three-mesh-bvh/-/three-mesh-bvh-0.8.3.tgz", - "integrity": "sha512-4G5lBaF+g2auKX3P0yqx+MJC6oVt6sB5k+CchS6Ob0qvH0YIhuUk1eYr7ktsIpY+albCqE80/FVQGV190PmiAg==", + "version": "0.9.9", + "resolved": "https://registry.npmjs.org/three-mesh-bvh/-/three-mesh-bvh-0.9.9.tgz", + "integrity": "sha512-FJKitcjvbALmeQRK+Sc+nLGorCpkrZBrbgJZFzhdyWboak37DZikn46hvQkNqSbJPm227ahYmS6k3N/GXaAyXw==", "license": "MIT", "peerDependencies": { "three": ">= 0.159.0" diff --git a/package.json b/package.json index a463ed3..2ce0706 100644 --- a/package.json +++ b/package.json @@ -27,7 +27,8 @@ "react-dom": "^19.2.4", "react-router-dom": "^7.14.0", "sqlite3": "^6.0.1", - "three": "^0.183.2" + "three": "^0.183.2", + "three-mesh-bvh": "^0.9.9" }, "devDependencies": { "@eslint/js": "^9.39.4", diff --git a/public/favicon.png b/public/favicon.png new file mode 100644 index 0000000..531abad Binary files /dev/null and b/public/favicon.png differ diff --git a/public/favicon.svg b/public/favicon.svg deleted file mode 100644 index 6893eb1..0000000 --- a/public/favicon.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/src/pages/GraphPage.css b/src/pages/GraphPage.css index cd394bf..adce869 100644 --- a/src/pages/GraphPage.css +++ b/src/pages/GraphPage.css @@ -282,6 +282,10 @@ border-color: rgba(255, 127, 200, 0.26); } +.graph-node--imageCompare { + border-color: rgba(255, 154, 98, 0.26); +} + .graph-node__card.image-card { width: 360px; cursor: grab; @@ -546,6 +550,164 @@ background: rgba(143, 245, 255, 0.1); } +.graph-node__compare-card { + width: 420px; + display: flex; + flex-direction: column; + gap: 0.9rem; +} + +.graph-node__compare-header { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 0.75rem; + cursor: grab; +} + +.graph-node__compare-header:active { + cursor: grabbing; +} + +.graph-node__compare-title-group { + min-width: 0; + flex: 1; + display: flex; + flex-direction: column; + gap: 0.45rem; +} + +.graph-node__compare-type { + width: fit-content; + display: inline-flex; + align-items: center; + padding: 0.22rem 0.5rem; + border: 1px solid rgba(255, 154, 98, 0.34); + border-radius: var(--radius-full); + background: rgba(255, 154, 98, 0.14); + color: #ffb189; + font-size: 0.58rem; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +.graph-node__compare-body { + display: flex; + flex-direction: column; + gap: 0.8rem; +} + +.graph-node__compare-stage { + position: relative; + overflow: hidden; + min-height: 400px; + border: 1px solid rgba(71, 72, 74, 0.18); + border-radius: 22px; + background: + linear-gradient(180deg, rgba(21, 23, 26, 0.96), rgba(13, 14, 17, 0.98)), + rgba(12, 14, 16, 0.98); +} + +.graph-node__compare-stage--active { + cursor: ew-resize; +} + +.graph-node__compare-image { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + object-fit: contain; + background: rgba(12, 14, 16, 0.98); + user-select: none; + pointer-events: none; +} + +.graph-node__compare-image--overlay { + border-right: 1px solid rgba(255, 255, 255, 0.08); +} + +.graph-node__compare-divider { + position: absolute; + top: 0; + bottom: 0; + width: 2px; + background: rgba(255, 154, 98, 0.92); + box-shadow: 0 0 0 1px rgba(12, 14, 16, 0.72); + transform: translateX(-50%); + pointer-events: none; +} + +.graph-node__compare-divider .material-symbols-outlined { + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + padding: 0.3rem; + border-radius: var(--radius-full); + background: rgba(18, 19, 21, 0.92); + color: #ffb189; + font-size: 17px; +} + +.graph-node__compare-placeholder { + min-height: 400px; + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 0.75rem; + padding: 0.9rem; +} + +.graph-node__compare-slot { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 0.55rem; + border: 1px dashed rgba(255, 154, 98, 0.24); + border-radius: 18px; + background: rgba(255, 154, 98, 0.06); + color: var(--on-surface-variant); + text-align: center; + padding: 1rem; +} + +.graph-node__compare-slot .material-symbols-outlined { + color: #ffb189; + font-size: 28px; +} + +.graph-node__compare-caption { + position: absolute; + right: 0.8rem; + bottom: 0.8rem; + left: 0.8rem; + display: flex; + justify-content: space-between; + gap: 0.75rem; + padding: 0.45rem 0.65rem; + border-radius: var(--radius-full); + /*background: rgba(18, 19, 21, 0.4);*/ + color: var(--on-surface); + /*backdrop-filter: blur(1px);*/ +} + +.graph-node__compare-caption span { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.graph-node__compare-refresh { + justify-content: center; +} + +.graph-node__compare-refresh:disabled { + opacity: 0.45; + cursor: not-allowed; +} + .graph-node__connector { position: absolute; z-index: 2; @@ -620,6 +782,10 @@ width: 240px; } + .graph-node__compare-card { + width: 320px; + } + .graph-node { padding-inline: 1.6rem; } diff --git a/src/pages/GraphPage.jsx b/src/pages/GraphPage.jsx index ef3400c..4944361 100644 --- a/src/pages/GraphPage.jsx +++ b/src/pages/GraphPage.jsx @@ -28,6 +28,8 @@ import './GraphPage.css' const DEFAULT_OUTPUT_ID = 'output-0' const DEFAULT_INPUT_ID = 'input-0' +const IMAGE_COMPARE_NODE_TYPE_NAME = 'Image Compare' +const IMAGE_COMPARE_INPUT_IDS = ['input-0', 'input-1'] const LEGACY_INPUT_ID = 'image-input' const DEFAULT_CUSTOM_API_TYPE = 'image-generation' const IMAGE_API_LIST = [ @@ -37,7 +39,7 @@ const IMAGE_API_LIST = [ { id: 'openai_gpt_image_1', name: 'OpenAI · gpt-image-1' }, { id: 'openai_gpt_image_1_5', name: 'OpenAI · gpt-image-1.5' } ] -const GRAPH_NODE_TYPE_OPTIONS = ['Image', 'Mesh', 'Number', 'Text', 'Boolean'] +const GRAPH_NODE_TYPE_OPTIONS = ['Image', 'Mesh', IMAGE_COMPARE_NODE_TYPE_NAME, 'Number', 'Text', 'Boolean'] const CONNECTOR_TYPE_META = { image: { key: 'image', label: 'Image', letter: 'I', color: '#8ff5ff', background: 'rgba(143, 245, 255, 0.14)' }, mesh: { key: 'mesh', label: 'Mesh', letter: 'M', color: '#ac89ff', background: 'rgba(172, 137, 255, 0.14)' }, @@ -57,6 +59,10 @@ function normalizeCustomApiType(type) { function getNodeKind(nodeTypeName = '') { const normalizedNodeType = String(nodeTypeName).trim().toLowerCase() + if (normalizedNodeType === 'image compare') { + return 'imageCompare' + } + if (['mesh', 'mesh gen'].includes(normalizedNodeType)) { return 'meshGen' } @@ -71,6 +77,10 @@ function getNodeKind(nodeTypeName = '') { function getDefaultNodeOutputType(nodeTypeName = '') { const nodeKind = getNodeKind(nodeTypeName) + if (nodeKind === 'imageCompare') { + return null + } + if (nodeKind === 'meshGen') { return 'mesh' } @@ -195,6 +205,16 @@ function getConnectorPosition(index, total) { } function buildInputConnectors(nodeId, currentNodes, currentEdges) { + const targetNode = currentNodes.find(node => node.id === String(nodeId)) + + if (targetNode?.data?.nodeKind === 'imageCompare') { + return IMAGE_COMPARE_INPUT_IDS.map(handleId => ({ + id: handleId, + type: 'image', + isConnected: currentEdges.some(edge => edge.target === String(nodeId) && (edge.targetHandle || DEFAULT_INPUT_ID) === handleId) + })) + } + const incomingEdges = currentEdges .filter(edge => edge.target === String(nodeId)) .sort((leftEdge, rightEdge) => compareHandleIds(leftEdge.targetHandle || DEFAULT_INPUT_ID, rightEdge.targetHandle || DEFAULT_INPUT_ID)) @@ -262,6 +282,14 @@ function getAssetPreviewUrl(filename) { return `http://localhost:3001/assets/${encodeURI(filename)}` } +function appendCacheBust(url, cacheKey) { + if (!url) { + return null + } + + return `${url}${url.includes('?') ? '&' : '?'}refresh=${encodeURIComponent(String(cacheKey))}` +} + function buildMeshEditorPath({ asset, projectId, nodeId, returnTo }) { const query = new URLSearchParams({ assetId: String(asset?.id || ''), @@ -1410,6 +1438,163 @@ function GraphAssetNode({ data }) { ) } +function GraphImageCompareNode({ data }) { + const [refreshKey, setRefreshKey] = useState(0) + const [comparePosition, setComparePosition] = useState(50) + const inputConnectors = data.inputConnectors || IMAGE_COMPARE_INPUT_IDS.map(id => ({ id, type: 'image', isConnected: false })) + const leftSource = (data.inputSources || []).find(source => source.connectorId === IMAGE_COMPARE_INPUT_IDS[0]) || null + const rightSource = (data.inputSources || []).find(source => source.connectorId === IMAGE_COMPARE_INPUT_IDS[1]) || null + const leftAsset = leftSource?.asset || null + const rightAsset = rightSource?.asset || null + const leftPreviewUrl = appendCacheBust(getAssetPreviewUrl(leftAsset?.thumbnail || leftAsset?.filename), refreshKey) + const rightPreviewUrl = appendCacheBust(getAssetPreviewUrl(rightAsset?.thumbnail || rightAsset?.filename), refreshKey) + const hasBothImages = Boolean(leftPreviewUrl && rightPreviewUrl) + const nodeDisplayName = data.name || data.nodeTypeName || IMAGE_COMPARE_NODE_TYPE_NAME + const connectedInputCount = inputConnectors.filter(connector => connector.isConnected).length + + useEffect(() => { + setComparePosition(50) + }, [leftPreviewUrl, rightPreviewUrl]) + + const handlePointerMove = useCallback((event) => { + if (!hasBothImages) { + return + } + + const bounds = event.currentTarget.getBoundingClientRect() + if (!bounds.width) { + return + } + + const nextPosition = ((event.clientX - bounds.left) / bounds.width) * 100 + setComparePosition(Math.max(0, Math.min(100, nextPosition))) + }, [hasBothImages]) + + return ( +
+ {inputConnectors.map((connector, index) => { + const connectorMeta = getConnectorTypeMeta(connector.type) + + return ( +
+ + + {connectorMeta.letter} + +
+ ) + })} + +
+
+
+ data.onNodeNameChange?.(data.id, event.target.value)} + onBlur={event => data.onNodeNameCommit?.(data.id, event.target.value)} + onKeyDown={event => { + if (event.key === 'Enter') { + event.preventDefault() + event.currentTarget.blur() + } + }} + /> + COMPARE +
+ + +
+ +
+
+ {hasBothImages ? ( + <> + {rightAsset?.name + {leftAsset?.name +
+ compare_arrows +
+ + ) : ( +
+ {[leftSource, rightSource].map((source, index) => ( +
+ image + {source?.label || `Connect image ${index + 1}`} +
+ ))} +
+ )} + +
+ {leftSource?.label || 'Left image'} + {rightSource?.label || 'Right image'} +
+
+ +

+ {hasBothImages + ? 'Move across the preview to inspect the differences between both inputs.' + : 'Connect two image outputs to enable the comparer.'} +

+ +
+ Inputs · {connectedInputCount}/2 connected +
+ + +
+
+
+ ) +} + function GraphValueNode({ data }) { const nodeKind = data.nodeKind const outputMeta = getConnectorTypeMeta(nodeKind) @@ -1526,6 +1711,7 @@ function GraphValueNode({ data }) { const flowNodeTypes = { image: GraphAssetNode, imageEdit: GraphAssetNode, + imageCompare: GraphImageCompareNode, meshGen: GraphAssetNode, number: GraphValueNode, text: GraphValueNode, @@ -2058,7 +2244,11 @@ export default function GraphPage({ project }) { const renderedNodes = useMemo(() => nodes.map(node => ({ ...node, - dragHandle: isValueNodeKind(node.data.nodeKind) ? '.graph-node__value-card' : '.graph-node__card', + dragHandle: isValueNodeKind(node.data.nodeKind) + ? '.graph-node__value-card' + : node.data.nodeKind === 'imageCompare' + ? '.graph-node__compare-header' + : '.graph-node__card', data: { ...node.data, inputConnectors: buildInputConnectors(node.id, nodes, edges), @@ -2964,7 +3154,20 @@ export default function GraphPage({ project }) { return } + const sourceNode = nodes.find(node => node.id === String(connection.source)) + const targetNode = nodes.find(node => node.id === String(connection.target)) + + if (!sourceNode || !targetNode) { + return + } + const targetHandleId = connection.targetHandle || DEFAULT_INPUT_ID + if (targetNode.data.nodeKind === 'imageCompare') { + if (!IMAGE_COMPARE_INPUT_IDS.includes(targetHandleId) || getNodeOutputType(sourceNode) !== 'image') { + return + } + } + if (edges.some(edge => edge.target === String(connection.target) && (edge.targetHandle || DEFAULT_INPUT_ID) === targetHandleId)) { return } @@ -2984,7 +3187,31 @@ export default function GraphPage({ project }) { return addEdge(nextEdge, currentEdges) }) - }, [createProjectConnection, edges, project.id, setEdges]) + }, [createProjectConnection, edges, nodes, project.id, setEdges]) + + const isValidConnection = useCallback((connection) => { + if (!connection.source || !connection.target) { + return false + } + + const sourceNode = nodes.find(node => node.id === String(connection.source)) + const targetNode = nodes.find(node => node.id === String(connection.target)) + + if (!sourceNode || !targetNode || sourceNode.id === targetNode.id) { + return false + } + + const targetHandleId = connection.targetHandle || DEFAULT_INPUT_ID + if (edges.some(edge => edge.target === String(connection.target) && (edge.targetHandle || DEFAULT_INPUT_ID) === targetHandleId)) { + return false + } + + if (targetNode.data.nodeKind === 'imageCompare') { + return IMAGE_COMPARE_INPUT_IDS.includes(targetHandleId) && getNodeOutputType(sourceNode) === 'image' + } + + return true + }, [edges, nodes]) const handlePaneClick = useCallback(() => { if (nodePicker) { @@ -3133,6 +3360,7 @@ export default function GraphPage({ project }) { const showEmptyState = !loading && nodes.length === 0 const minimapNodeColor = useCallback((node) => { if (node.type === 'meshGen') return '#79e388' + if (node.type === 'imageCompare') return '#ff9a62' if (node.type === 'text') return '#ffd36e' if (node.type === 'boolean') return '#ff7fc8' if (node.type === 'number') return '#79e388' @@ -3204,6 +3432,7 @@ export default function GraphPage({ project }) { onNodesChange={onNodesChange} onEdgesChange={onEdgesChange} onConnect={handleConnect} + isValidConnection={isValidConnection} onPaneClick={handlePaneClick} onPaneContextMenu={handlePaneContextMenu} onNodeDragStop={handleNodeDragStop} diff --git a/src/pages/MeshEditorPage.css b/src/pages/MeshEditorPage.css index 206c9f3..dffed28 100644 --- a/src/pages/MeshEditorPage.css +++ b/src/pages/MeshEditorPage.css @@ -17,6 +17,7 @@ .mesh-editor-shell { flex: 1; + min-height: 0; width: 100%; max-width: 1440px; margin: 0 auto; @@ -64,6 +65,21 @@ gap: 0.45rem; } +.mesh-editor-toolbar__save-panel { + display: flex; + flex-direction: column; + gap: 0.45rem; + min-width: 220px; +} + +.mesh-editor-toolbar__save-actions { + flex-wrap: nowrap; +} + +.mesh-editor-toolbar__save-actions .mesh-editor-btn { + flex: 1; +} + .mesh-editor-toolbar__stats { display: inline-flex; gap: 0.75rem; @@ -109,12 +125,14 @@ display: grid; grid-template-columns: 280px minmax(0, 1fr); gap: 1rem; + align-items: start; } .mesh-editor-sidebar { display: flex; flex-direction: column; gap: 1rem; + min-height: 0; } .mesh-editor-panel { @@ -157,6 +175,26 @@ flex-direction: column; } +.mesh-editor-panel--actions { + display: grid; + grid-template-rows: auto minmax(0, 1fr); + max-height: calc(100vh - 320px); + min-height: 0; +} + +.mesh-editor-panel__scroll { + min-height: 0; + overflow-y: auto; + overscroll-behavior: contain; + -webkit-overflow-scrolling: touch; + padding-right: 0.25rem; +} + +.mesh-editor-panel--actions .mesh-editor-actions--column { + flex-wrap: nowrap; + align-content: flex-start; +} + .mesh-editor-toggle, .mesh-editor-btn { min-height: 40px; @@ -201,7 +239,6 @@ .mesh-editor-canvas-shell { position: relative; - flex: 1; min-height: 760px; height: clamp(760px, calc(100vh - 210px), 1400px); overflow: hidden; @@ -252,6 +289,10 @@ flex-wrap: wrap; } + .mesh-editor-toolbar__save-panel { + min-width: 260px; + } + .mesh-editor-toolbar__stats { justify-content: flex-start; } @@ -282,10 +323,24 @@ min-width: 0; } + .mesh-editor-toolbar__save-panel { + width: 100%; + min-width: 0; + } + + .mesh-editor-toolbar__save-actions { + flex-wrap: wrap; + } + .mesh-editor-workspace { grid-template-columns: 1fr; } + .mesh-editor-panel--actions, + .mesh-editor-panel__scroll { + max-height: none; + } + .mesh-editor-canvas-shell { min-height: 620px; height: clamp(620px, calc(100vh - 240px), 1000px); diff --git a/src/pages/MeshEditorPage.jsx b/src/pages/MeshEditorPage.jsx index 3cafe08..93ec766 100644 --- a/src/pages/MeshEditorPage.jsx +++ b/src/pages/MeshEditorPage.jsx @@ -9,6 +9,8 @@ import SettingsModal from '../components/SettingsModal' import { useProjects } from '../context/ProjectContext' import { createMeshThumbnailFile } from '../utils/meshThumbnail' import { + bridgeSelectedHoleSegments, + bridgeAndFillSelectedHole, deleteSelectedFaces, deleteSelectedVertices, exportGeometryToObj, @@ -141,6 +143,7 @@ export default function MeshEditorPage() { const [showSettings, setShowSettings] = useState(false) const [geometry, setGeometry] = useState(null) + const [geometryRevision, setGeometryRevision] = useState(0) const [loading, setLoading] = useState(true) const [saving, setSaving] = useState(false) const [error, setError] = useState('') @@ -148,7 +151,7 @@ export default function MeshEditorPage() { const [selectionMode, setSelectionMode] = useState('face') const [selectedFaceIndices, setSelectedFaceIndices] = useState([]) const [selectedVertexIndices, setSelectedVertexIndices] = useState([]) - const [holeLoops, setHoleLoops] = useState([]) + const [_holeLoops, setHoleLoops] = useState([]) const [meshName, setMeshName] = useState(searchParams.get('name') || 'Mesh') const [selectionBox, setSelectionBox] = useState(null) @@ -163,6 +166,8 @@ export default function MeshEditorPage() { const cameraRef = useRef(null) const dragStateRef = useRef(null) + useEffect(() => () => geometry?.dispose?.(), [geometry]) + useEffect(() => { let cancelled = false @@ -180,6 +185,7 @@ export default function MeshEditorPage() { if (!cancelled) { setGeometry(loadedGeometry) + setGeometryRevision(0) setSelectedFaceIndices([]) setSelectedVertexIndices([]) setHoleLoops([]) @@ -205,7 +211,7 @@ export default function MeshEditorPage() { const stats = useMemo(() => ({ vertices: geometry?.attributes?.position?.count || 0, faces: geometryFaceCount(geometry) - }), [geometry]) + }), [geometry, geometryRevision]) const availableHoleLoops = useMemo(() => { if (!geometry) { return [] @@ -216,7 +222,16 @@ export default function MeshEditorPage() { selectedFaceIndices, selectedVertexIndices }) - }, [geometry, selectedFaceIndices, selectedVertexIndices, selectionMode]) + }, [geometry, geometryRevision, selectedFaceIndices, selectedVertexIndices, selectionMode]) + const selectionMesh = useMemo(() => { + if (!geometry) { + return null + } + + const mesh = new THREE.Mesh(geometry) + mesh.updateMatrixWorld(true) + return mesh + }, [geometry]) const resetSelection = useCallback(() => { setSelectedFaceIndices([]) @@ -266,12 +281,6 @@ export default function MeshEditorPage() { }) }, []) - const createSelectionMesh = useCallback(() => { - const mesh = new THREE.Mesh(geometry) - mesh.updateMatrixWorld(true) - return mesh - }, [geometry]) - const createRectangleSamplePoints = useCallback((bounds) => { const width = Math.max(1, bounds.right - bounds.left) const height = Math.max(1, bounds.bottom - bounds.top) @@ -307,15 +316,15 @@ export default function MeshEditorPage() { } const raycaster = new THREE.Raycaster() + raycaster.firstHitOnly = true const pointer = new THREE.Vector2( (point.x / rect.width) * 2 - 1, -((point.y / rect.height) * 2 - 1) ) raycaster.setFromCamera(pointer, cameraRef.current) - - const mesh = createSelectionMesh() - const [intersection] = raycaster.intersectObject(mesh, false) + selectionMesh.updateMatrixWorld(true) + const [intersection] = raycaster.intersectObject(selectionMesh, false) if (!intersection) { if (!isMultiSelect) { @@ -335,7 +344,7 @@ export default function MeshEditorPage() { if (intersection.faceIndex !== undefined && intersection.faceIndex !== null) { applySelection('face', [intersection.faceIndex], isMultiSelect) } - }, [applySelection, createSelectionMesh, geometry, resetSelection, selectionMode]) + }, [applySelection, geometry, resetSelection, selectionMesh, selectionMode]) const selectWithinRectangle = useCallback((startPoint, endPoint, isMultiSelect) => { if (!geometry || !cameraRef.current || !canvasShellRef.current) { @@ -345,8 +354,9 @@ export default function MeshEditorPage() { const rect = canvasShellRef.current.getBoundingClientRect() const bounds = getRectangleBounds(startPoint, endPoint) const raycaster = new THREE.Raycaster() - const mesh = createSelectionMesh() + raycaster.firstHitOnly = true const samplePoints = createRectangleSamplePoints(bounds) + selectionMesh.updateMatrixWorld(true) if (selectionMode === 'vertex') { const nextVertices = new Set() @@ -358,7 +368,7 @@ export default function MeshEditorPage() { ) raycaster.setFromCamera(pointer, cameraRef.current) - const [intersection] = raycaster.intersectObject(mesh, false) + const [intersection] = raycaster.intersectObject(selectionMesh, false) if (!intersection) { return @@ -383,7 +393,7 @@ export default function MeshEditorPage() { ) raycaster.setFromCamera(pointer, cameraRef.current) - const [intersection] = raycaster.intersectObject(mesh, false) + const [intersection] = raycaster.intersectObject(selectionMesh, false) if (intersection?.faceIndex !== undefined && intersection.faceIndex !== null) { nextFaces.add(intersection.faceIndex) @@ -391,7 +401,7 @@ export default function MeshEditorPage() { }) applySelection('face', [...nextFaces].sort((left, right) => left - right), isMultiSelect) - }, [applySelection, createRectangleSamplePoints, createSelectionMesh, geometry, selectionMode]) + }, [applySelection, createRectangleSamplePoints, geometry, selectionMesh, selectionMode]) const getPointerPosition = useCallback((event) => { const rect = canvasShellRef.current?.getBoundingClientRect() @@ -481,6 +491,7 @@ export default function MeshEditorPage() { const applyGeometryUpdate = useCallback((nextGeometry, nextHoleLoops = []) => { setGeometry(nextGeometry) + setGeometryRevision(current => current + 1) setHoleLoops(nextHoleLoops) setSelectedFaceIndices([]) setSelectedVertexIndices([]) @@ -526,13 +537,35 @@ export default function MeshEditorPage() { applyGeometryUpdate(subdivideSelectedFaces(geometry, selectedFaceIndices), []) }, [applyGeometryUpdate, geometry, selectedFaceIndices]) + const handleBridge = useCallback(() => { + if (!geometry || selectionMode !== 'vertex') { + return + } + + const result = bridgeSelectedHoleSegments(geometry, selectedVertexIndices) + if (!result.applied) { + setFeedback('Select two boundary vertex segments on the same hole to bridge them.') + return + } + + applyGeometryUpdate(result.geometry, result.holeLoops) + }, [applyGeometryUpdate, geometry, selectedVertexIndices, selectionMode]) + const handleFillHole = useCallback(() => { if (!geometry || availableHoleLoops.length === 0) { return } + if (selectionMode === 'vertex') { + const result = bridgeAndFillSelectedHole(geometry, selectedVertexIndices) + if (result.applied) { + applyGeometryUpdate(result.geometry, []) + return + } + } + applyGeometryUpdate(fillHoleLoops(geometry, availableHoleLoops), []) - }, [applyGeometryUpdate, availableHoleLoops, geometry]) + }, [applyGeometryUpdate, availableHoleLoops, geometry, selectedVertexIndices, selectionMode]) const handleSave = useCallback(async (saveMode) => { if (!geometry || saving) { @@ -603,6 +636,7 @@ export default function MeshEditorPage() { const smoothDisabled = selectedVertexIndices.length === 0 const mergeDisabled = selectedVertexIndices.length < 2 const subdivideDisabled = selectedFaceIndices.length === 0 + const bridgeDisabled = selectionMode !== 'vertex' || selectedVertexIndices.length < 4 const fillDisabled = availableHoleLoops.length === 0 return ( @@ -626,6 +660,13 @@ export default function MeshEditorPage() { setMeshName(event.target.value)} /> +
+ Save +
+ + +
+
{stats.vertices} vertices @@ -667,25 +708,21 @@ export default function MeshEditorPage() {
Left mouse drag selects with a rectangle. Shift+drag adds or removes items. + For difficult holes, switch to Vertices and select two boundary segments on the same hole, then use Bridge or Fill hole. Middle mouse drag rotates the mesh.
Actions -
- - - - - -
-
- -
- Save -
- - +
+
+ + + + + + +
diff --git a/src/pages/ProjectsPage.jsx b/src/pages/ProjectsPage.jsx index 64e3728..393f97e 100644 --- a/src/pages/ProjectsPage.jsx +++ b/src/pages/ProjectsPage.jsx @@ -18,6 +18,14 @@ const STATUS_MAP = { } const CHANGE_LOG_ENTRIES = [ + { + version: 'v0.1.1', + date: '2026-04-21', + items: [ + 'Added Graph Node "Image Compare"', + 'Improved a bit the Mesh Editor (not good yet)', + ], + }, { version: 'v0.1.0', date: '2026-04-19', diff --git a/src/utils/meshEditor.js b/src/utils/meshEditor.js index 13a63cd..528dc38 100644 --- a/src/utils/meshEditor.js +++ b/src/utils/meshEditor.js @@ -5,6 +5,199 @@ import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader.js' import { PLYLoader } from 'three/examples/jsm/loaders/PLYLoader.js' import { STLLoader } from 'three/examples/jsm/loaders/STLLoader.js' import { mergeGeometries, mergeVertices } from 'three/examples/jsm/utils/BufferGeometryUtils.js' +import { acceleratedRaycast, computeBoundsTree, disposeBoundsTree } from 'three-mesh-bvh' + +if (THREE.BufferGeometry.prototype.computeBoundsTree !== computeBoundsTree) { + THREE.BufferGeometry.prototype.computeBoundsTree = computeBoundsTree +} + +if (THREE.BufferGeometry.prototype.disposeBoundsTree !== disposeBoundsTree) { + THREE.BufferGeometry.prototype.disposeBoundsTree = disposeBoundsTree +} + +if (THREE.Mesh.prototype.raycast !== acceleratedRaycast) { + THREE.Mesh.prototype.raycast = acceleratedRaycast +} + +function invalidateGeometryAnalysis(geometry) { + if (!geometry?.userData) { + return + } + + delete geometry.userData.meshEditorBoundaryCache +} + +function finalizeGeometry(geometry, { rebuildBoundsTree = true } = {}) { + if (!geometry) { + return geometry + } + + if (!geometry.attributes.normal) { + geometry.computeVertexNormals() + } + + geometry.computeBoundingBox() + geometry.computeBoundingSphere() + invalidateGeometryAnalysis(geometry) + + if (rebuildBoundsTree && geometry.computeBoundsTree) { + geometry.disposeBoundsTree?.() + geometry.computeBoundsTree() + } + + return geometry +} + +function markAttributeUpdateRange(attribute, startComponent, componentCount) { + if (!attribute || componentCount <= 0) { + return + } + + if (typeof attribute.clearUpdateRanges === 'function') { + attribute.clearUpdateRanges() + } + + if (typeof attribute.addUpdateRange === 'function') { + attribute.addUpdateRange(startComponent, componentCount) + } else if (attribute.updateRange) { + attribute.updateRange.offset = startComponent + attribute.updateRange.count = componentCount + } + + attribute.needsUpdate = true +} + +function buildVertexFaceMap(indices = []) { + const vertexFaces = new Map() + + const addFace = (vertexIndex, faceIndex) => { + if (!vertexFaces.has(vertexIndex)) { + vertexFaces.set(vertexIndex, []) + } + + vertexFaces.get(vertexIndex).push(faceIndex) + } + + for (let faceIndex = 0; faceIndex < indices.length / 3; faceIndex += 1) { + addFace(indices[faceIndex * 3], faceIndex) + addFace(indices[faceIndex * 3 + 1], faceIndex) + addFace(indices[faceIndex * 3 + 2], faceIndex) + } + + return vertexFaces +} + +function recomputeVertexNormalsLocally(geometry, changedVertexIndices = []) { + if (!geometry?.index || changedVertexIndices.length === 0) { + return + } + + const positionAttribute = geometry.attributes.position + let normalAttribute = geometry.attributes.normal + + if (!positionAttribute) { + return + } + + if (!normalAttribute || normalAttribute.count !== positionAttribute.count) { + normalAttribute = new THREE.BufferAttribute(new Float32Array(positionAttribute.count * 3), 3) + geometry.setAttribute('normal', normalAttribute) + geometry.computeVertexNormals() + return + } + + const indices = geometry.index.array + const positions = positionAttribute.array + const normals = normalAttribute.array + const vertexFaces = buildVertexFaceMap(indices) + const affectedFaces = new Set() + const affectedVertices = new Set() + + changedVertexIndices.forEach(vertexIndex => { + ;(vertexFaces.get(vertexIndex) || []).forEach(faceIndex => { + affectedFaces.add(faceIndex) + affectedVertices.add(indices[faceIndex * 3]) + affectedVertices.add(indices[faceIndex * 3 + 1]) + affectedVertices.add(indices[faceIndex * 3 + 2]) + }) + }) + + affectedVertices.forEach(vertexIndex => { + const offset = vertexIndex * 3 + normals[offset] = 0 + normals[offset + 1] = 0 + normals[offset + 2] = 0 + }) + + const ab = new THREE.Vector3() + const ac = new THREE.Vector3() + const faceNormal = new THREE.Vector3() + + affectedFaces.forEach(faceIndex => { + const a = indices[faceIndex * 3] + const b = indices[faceIndex * 3 + 1] + const c = indices[faceIndex * 3 + 2] + const aOffset = a * 3 + const bOffset = b * 3 + const cOffset = c * 3 + + ab.set( + positions[bOffset] - positions[aOffset], + positions[bOffset + 1] - positions[aOffset + 1], + positions[bOffset + 2] - positions[aOffset + 2] + ) + ac.set( + positions[cOffset] - positions[aOffset], + positions[cOffset + 1] - positions[aOffset + 1], + positions[cOffset + 2] - positions[aOffset + 2] + ) + + faceNormal.crossVectors(ab, ac) + + normals[aOffset] += faceNormal.x + normals[aOffset + 1] += faceNormal.y + normals[aOffset + 2] += faceNormal.z + normals[bOffset] += faceNormal.x + normals[bOffset + 1] += faceNormal.y + normals[bOffset + 2] += faceNormal.z + normals[cOffset] += faceNormal.x + normals[cOffset + 1] += faceNormal.y + normals[cOffset + 2] += faceNormal.z + }) + + const vertexNormal = new THREE.Vector3() + let minVertexIndex = Number.POSITIVE_INFINITY + let maxVertexIndex = Number.NEGATIVE_INFINITY + + affectedVertices.forEach(vertexIndex => { + const offset = vertexIndex * 3 + vertexNormal.set(normals[offset], normals[offset + 1], normals[offset + 2]).normalize() + normals[offset] = Number.isFinite(vertexNormal.x) ? vertexNormal.x : 0 + normals[offset + 1] = Number.isFinite(vertexNormal.y) ? vertexNormal.y : 0 + normals[offset + 2] = Number.isFinite(vertexNormal.z) ? vertexNormal.z : 0 + minVertexIndex = Math.min(minVertexIndex, vertexIndex) + maxVertexIndex = Math.max(maxVertexIndex, vertexIndex) + }) + + if (Number.isFinite(minVertexIndex) && Number.isFinite(maxVertexIndex)) { + markAttributeUpdateRange(normalAttribute, minVertexIndex * 3, (maxVertexIndex - minVertexIndex + 1) * 3) + } else { + normalAttribute.needsUpdate = true + } +} + +function refitSpatialIndex(geometry) { + if (!geometry) { + return + } + + if (geometry.boundsTree?.refit) { + geometry.boundsTree.refit() + return + } + + geometry.computeBoundsTree?.() +} function getExtensionFromUrl(url = '') { const sanitizedUrl = String(url).split('?')[0].toLowerCase() @@ -49,9 +242,7 @@ function createMergedGeometryFromObject(object) { weldedGeometry.computeVertexNormals() } - weldedGeometry.computeBoundingBox() - weldedGeometry.computeBoundingSphere() - return weldedGeometry + return finalizeGeometry(weldedGeometry) } async function loadGeometryFromUrl(url) { @@ -85,9 +276,264 @@ function createIndexedGeometry(positions = [], indices = []) { geometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3)) geometry.setIndex(indices) geometry.computeVertexNormals() - geometry.computeBoundingBox() - geometry.computeBoundingSphere() - return geometry + return finalizeGeometry(geometry) +} + +function createIndexBuffer(indices = [], vertexCount = 0) { + const IndexArray = vertexCount > 65535 ? Uint32Array : Uint16Array + return new THREE.BufferAttribute(new IndexArray(indices), 1) +} + +function replaceGeometryData(geometry, positions = [], indices = []) { + geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(positions), 3)) + geometry.setIndex(createIndexBuffer(indices, positions.length / 3)) + geometry.deleteAttribute('normal') + geometry.computeVertexNormals() + return finalizeGeometry(geometry) +} + +function computeLoopNormal(loop = [], positions = []) { + const normal = new THREE.Vector3() + + for (let index = 0; index < loop.length; index += 1) { + const currentOffset = loop[index] * 3 + const nextOffset = loop[(index + 1) % loop.length] * 3 + const currentX = positions[currentOffset] + const currentY = positions[currentOffset + 1] + const currentZ = positions[currentOffset + 2] + const nextX = positions[nextOffset] + const nextY = positions[nextOffset + 1] + const nextZ = positions[nextOffset + 2] + + normal.x += (currentY - nextY) * (currentZ + nextZ) + normal.y += (currentZ - nextZ) * (currentX + nextX) + normal.z += (currentX - nextX) * (currentY + nextY) + } + + return normal.normalize() +} + +function projectLoopToPlane(loop = [], positions = [], dominantAxis = 'z') { + return loop.map(vertexIndex => { + const offset = vertexIndex * 3 + const x = positions[offset] + const y = positions[offset + 1] + const z = positions[offset + 2] + + if (dominantAxis === 'x') { + return new THREE.Vector2(y, z) + } + + if (dominantAxis === 'y') { + return new THREE.Vector2(x, z) + } + + return new THREE.Vector2(x, y) + }) +} + +function getTriangleOrientation(indices, positions, expectedNormal) { + const aOffset = indices[0] * 3 + const bOffset = indices[1] * 3 + const cOffset = indices[2] * 3 + const ab = new THREE.Vector3( + positions[bOffset] - positions[aOffset], + positions[bOffset + 1] - positions[aOffset + 1], + positions[bOffset + 2] - positions[aOffset + 2] + ) + const ac = new THREE.Vector3( + positions[cOffset] - positions[aOffset], + positions[cOffset + 1] - positions[aOffset + 1], + positions[cOffset + 2] - positions[aOffset + 2] + ) + + return ab.cross(ac).dot(expectedNormal) +} + +function triangulateHoleLoop(loop = [], positions = []) { + if (loop.length < 3) { + return [] + } + + const loopNormal = computeLoopNormal(loop, positions) + + if (!Number.isFinite(loopNormal.lengthSq()) || loopNormal.lengthSq() === 0) { + return [] + } + + const absNormal = { + x: Math.abs(loopNormal.x), + y: Math.abs(loopNormal.y), + z: Math.abs(loopNormal.z) + } + + const dominantAxis = absNormal.x > absNormal.y && absNormal.x > absNormal.z + ? 'x' + : absNormal.y > absNormal.z + ? 'y' + : 'z' + + const projectedLoop = projectLoopToPlane(loop, positions, dominantAxis) + const triangles = THREE.ShapeUtils.triangulateShape(projectedLoop, []) + + if (!Array.isArray(triangles) || triangles.length === 0) { + return [] + } + + return triangles + .map(([aIndex, bIndex, cIndex]) => { + const triangle = [loop[aIndex], loop[bIndex], loop[cIndex]] + + if (triangle[0] === triangle[1] || triangle[1] === triangle[2] || triangle[2] === triangle[0]) { + return null + } + + if (getTriangleOrientation(triangle, positions, loopNormal) < 0) { + return [triangle[0], triangle[2], triangle[1]] + } + + return triangle + }) + .filter(Boolean) +} + +function triangulateHoleLoopFallback(loop = []) { + const triangles = [] + + for (let index = 1; index < loop.length - 1; index += 1) { + triangles.push([loop[0], loop[index], loop[index + 1]]) + } + + return triangles +} + +function getVertexDistanceSquared(positions = [], leftVertexIndex, rightVertexIndex) { + const leftOffset = leftVertexIndex * 3 + const rightOffset = rightVertexIndex * 3 + const dx = positions[leftOffset] - positions[rightOffset] + const dy = positions[leftOffset + 1] - positions[rightOffset + 1] + const dz = positions[leftOffset + 2] - positions[rightOffset + 2] + return dx * dx + dy * dy + dz * dz +} + +function orientTriangleToNormal(triangle = [], positions = [], normal = new THREE.Vector3(0, 0, 1)) { + if (triangle.length !== 3) { + return triangle + } + + return getTriangleOrientation(triangle, positions, normal) < 0 + ? [triangle[0], triangle[2], triangle[1]] + : triangle +} + +function getSelectedBoundaryGroups(loop = [], selectedVertexSet = new Set()) { + if (loop.length === 0) { + return [] + } + + const groups = [] + + for (let index = 0; index < loop.length; index += 1) { + const vertexIndex = loop[index] + if (!selectedVertexSet.has(vertexIndex)) { + continue + } + + const previousVertex = loop[(index - 1 + loop.length) % loop.length] + if (selectedVertexSet.has(previousVertex)) { + continue + } + + const group = [] + let cursor = index + + while (selectedVertexSet.has(loop[cursor])) { + group.push(loop[cursor]) + cursor = (cursor + 1) % loop.length + if (cursor === index) { + break + } + } + + groups.push(group) + } + + return groups +} + +function alignBridgeChains(chainA = [], chainB = [], positions = []) { + const directScore = getVertexDistanceSquared(positions, chainA[0], chainB[0]) + + getVertexDistanceSquared(positions, chainA[chainA.length - 1], chainB[chainB.length - 1]) + const reversed = [...chainB].reverse() + const reversedScore = getVertexDistanceSquared(positions, chainA[0], reversed[0]) + + getVertexDistanceSquared(positions, chainA[chainA.length - 1], reversed[reversed.length - 1]) + + return reversedScore < directScore ? reversed : chainB +} + +function buildBridgeTriangles(chainA = [], chainB = [], positions = [], normal = new THREE.Vector3(0, 0, 1)) { + const triangles = [] + let leftIndex = 0 + let rightIndex = 0 + + while (leftIndex < chainA.length - 1 || rightIndex < chainB.length - 1) { + let triangle = null + + if (leftIndex === chainA.length - 1) { + triangle = [chainA[leftIndex], chainB[rightIndex], chainB[rightIndex + 1]] + rightIndex += 1 + } else if (rightIndex === chainB.length - 1) { + triangle = [chainA[leftIndex], chainA[leftIndex + 1], chainB[rightIndex]] + leftIndex += 1 + } else { + const advanceLeftScore = getVertexDistanceSquared(positions, chainA[leftIndex + 1], chainB[rightIndex]) + const advanceRightScore = getVertexDistanceSquared(positions, chainA[leftIndex], chainB[rightIndex + 1]) + + if (advanceLeftScore <= advanceRightScore) { + triangle = [chainA[leftIndex], chainA[leftIndex + 1], chainB[rightIndex]] + leftIndex += 1 + } else { + triangle = [chainA[leftIndex], chainB[rightIndex], chainB[rightIndex + 1]] + rightIndex += 1 + } + } + + if (triangle[0] !== triangle[1] && triangle[1] !== triangle[2] && triangle[2] !== triangle[0]) { + triangles.push(orientTriangleToNormal(triangle, positions, normal)) + } + } + + return triangles +} + +function getBridgeAndFillCandidate(geometry, selectedVertexIndices = []) { + if (!geometry?.index || selectedVertexIndices.length < 4) { + return null + } + + const selectedVertexSet = new Set(selectedVertexIndices) + const { loops } = getOrCreateBoundaryCache(geometry) + let bestCandidate = null + + loops.forEach(loop => { + const groups = getSelectedBoundaryGroups(loop, selectedVertexSet) + .filter(group => group.length >= 2) + + if (groups.length !== 2) { + return + } + + const score = groups[0].length + groups[1].length + if (!bestCandidate || score > bestCandidate.score) { + bestCandidate = { + loop, + groups, + score + } + } + }) + + return bestCandidate } function geometryToMeshData(geometry) { @@ -229,11 +675,13 @@ function buildHoleLoops(meshData, removedFaceIndices = []) { return loops } -function getBoundaryEdgeRecords(meshData) { +function getBoundaryEdgeRecords(indices = []) { const edgeRecords = new Map() - for (let faceIndex = 0; faceIndex < meshData.indices.length / 3; faceIndex += 1) { - const [a, b, c] = getFace(meshData, faceIndex) + for (let faceIndex = 0; faceIndex < indices.length / 3; faceIndex += 1) { + const a = indices[faceIndex * 3] + const b = indices[faceIndex * 3 + 1] + const c = indices[faceIndex * 3 + 2] ;[[a, b], [b, c], [c, a]].forEach(([start, end]) => { const key = start < end ? `${start}:${end}` : `${end}:${start}` @@ -257,6 +705,26 @@ function getBoundaryEdgeRecords(meshData) { return [...edgeRecords.values()].filter(record => record.count === 1) } +function getOrCreateBoundaryCache(geometry) { + if (!geometry?.index) { + return { boundaryEdges: [], loops: [], boundaryEdgeMap: new Map() } + } + + if (geometry.userData?.meshEditorBoundaryCache) { + return geometry.userData.meshEditorBoundaryCache + } + + const boundaryEdges = getBoundaryEdgeRecords(geometry.index.array) + const cache = { + boundaryEdges, + loops: buildLoopsFromBoundaryEdges(boundaryEdges), + boundaryEdgeMap: new Map(boundaryEdges.map(edge => [edge.key, edge])) + } + + geometry.userData.meshEditorBoundaryCache = cache + return cache +} + function buildLoopsFromBoundaryEdges(boundaryEdges = []) { const adjacency = new Map() const visitedEdges = new Set() @@ -333,31 +801,25 @@ function buildLoopsFromBoundaryEdges(boundaryEdges = []) { } export function getGeometryHoleLoops(geometry) { - const meshData = geometryToMeshData(geometry) - - if (meshData.indices.length === 0) { + if (!geometry?.index?.count) { return [] } - return buildLoopsFromBoundaryEdges(getBoundaryEdgeRecords(meshData)) + return getOrCreateBoundaryCache(geometry).loops } export function getSelectedHoleLoops(geometry, { selectionMode = 'face', selectedFaceIndices = [], selectedVertexIndices = [] } = {}) { - const meshData = geometryToMeshData(geometry) - - if (meshData.indices.length === 0) { + if (!geometry?.index?.count) { return [] } - const boundaryEdges = getBoundaryEdgeRecords(meshData) - const loops = buildLoopsFromBoundaryEdges(boundaryEdges) + const { boundaryEdgeMap, loops } = getOrCreateBoundaryCache(geometry) if (selectionMode === 'vertex') { const selectedVertexSet = new Set(selectedVertexIndices) return loops.filter(loop => loop.some(vertexIndex => selectedVertexSet.has(vertexIndex))) } - const boundaryEdgeMap = new Map(boundaryEdges.map(edge => [edge.key, edge])) const selectedFaceSet = new Set(selectedFaceIndices) return loops.filter(loop => loop.some((vertexIndex, index) => { @@ -417,9 +879,16 @@ export function deleteSelectedVertices(geometry, selectedVertexIndices = []) { } export function smoothSelectedVertices(geometry, selectedVertexIndices = [], strength = 0.45) { - const meshData = geometryToMeshData(geometry) - const nextPositions = [...meshData.positions] - const neighbors = buildNeighborMap(meshData.indices) + if (!geometry?.attributes?.position || !geometry?.index || selectedVertexIndices.length === 0) { + return geometry?.clone?.() || geometry + } + + const positionAttribute = geometry.attributes.position + const positions = positionAttribute.array + const indices = geometry.index.array + const neighbors = buildNeighborMap(indices) + let minVertexIndex = Number.POSITIVE_INFINITY + let maxVertexIndex = Number.NEGATIVE_INFINITY selectedVertexIndices.forEach(vertexIndex => { const adjacent = [...(neighbors.get(vertexIndex) || [])] @@ -430,25 +899,37 @@ export function smoothSelectedVertices(geometry, selectedVertexIndices = [], str const average = new THREE.Vector3() adjacent.forEach(neighborIndex => { average.add(new THREE.Vector3( - meshData.positions[neighborIndex * 3], - meshData.positions[neighborIndex * 3 + 1], - meshData.positions[neighborIndex * 3 + 2] + positions[neighborIndex * 3], + positions[neighborIndex * 3 + 1], + positions[neighborIndex * 3 + 2] )) }) average.multiplyScalar(1 / adjacent.length) const current = new THREE.Vector3( - meshData.positions[vertexIndex * 3], - meshData.positions[vertexIndex * 3 + 1], - meshData.positions[vertexIndex * 3 + 2] + positions[vertexIndex * 3], + positions[vertexIndex * 3 + 1], + positions[vertexIndex * 3 + 2] ).lerp(average, strength) - nextPositions[vertexIndex * 3] = current.x - nextPositions[vertexIndex * 3 + 1] = current.y - nextPositions[vertexIndex * 3 + 2] = current.z + positions[vertexIndex * 3] = current.x + positions[vertexIndex * 3 + 1] = current.y + positions[vertexIndex * 3 + 2] = current.z + minVertexIndex = Math.min(minVertexIndex, vertexIndex) + maxVertexIndex = Math.max(maxVertexIndex, vertexIndex) }) - return createIndexedGeometry(nextPositions, meshData.indices) + if (Number.isFinite(minVertexIndex) && Number.isFinite(maxVertexIndex)) { + markAttributeUpdateRange(positionAttribute, minVertexIndex * 3, (maxVertexIndex - minVertexIndex + 1) * 3) + } else { + positionAttribute.needsUpdate = true + } + + recomputeVertexNormalsLocally(geometry, selectedVertexIndices) + geometry.computeBoundingBox() + geometry.computeBoundingSphere() + refitSpatialIndex(geometry) + return geometry } export function mergeSelectedVertices(geometry, selectedVertexIndices = []) { @@ -532,7 +1013,6 @@ export function fillHoleLoops(geometry, holeLoops = []) { } const meshData = geometryToMeshData(geometry) - const nextPositions = [...meshData.positions] const nextIndices = [...meshData.indices] holeLoops.forEach(loop => { @@ -540,45 +1020,97 @@ export function fillHoleLoops(geometry, holeLoops = []) { return } - const centroid = new THREE.Vector3() - loop.forEach(vertexIndex => { - centroid.add(new THREE.Vector3( - meshData.positions[vertexIndex * 3], - meshData.positions[vertexIndex * 3 + 1], - meshData.positions[vertexIndex * 3 + 2] - )) - }) - centroid.multiplyScalar(1 / loop.length) - - const centerIndex = nextPositions.length / 3 - nextPositions.push(centroid.x, centroid.y, centroid.z) - - for (let index = 0; index < loop.length; index += 1) { - const current = loop[index] - const next = loop[(index + 1) % loop.length] - nextIndices.push(current, next, centerIndex) - } + const triangles = triangulateHoleLoop(loop, meshData.positions) + const safeTriangles = triangles.length > 0 ? triangles : triangulateHoleLoopFallback(loop) + safeTriangles.forEach(triangle => nextIndices.push(...triangle)) }) - return createIndexedGeometry(nextPositions, nextIndices) + return replaceGeometryData(geometry, meshData.positions, nextIndices) +} + +export function bridgeSelectedHoleSegments(geometry, selectedVertexIndices = []) { + const candidate = getBridgeAndFillCandidate(geometry, selectedVertexIndices) + if (!candidate) { + return { + geometry, + applied: false, + holeLoops: [] + } + } + + const meshData = geometryToMeshData(geometry) + const loopNormal = computeLoopNormal(candidate.loop, meshData.positions) + const chainA = candidate.groups[0] + const chainB = alignBridgeChains(candidate.groups[0], candidate.groups[1], meshData.positions) + const bridgeTriangles = buildBridgeTriangles(chainA, chainB, meshData.positions, loopNormal) + + if (bridgeTriangles.length === 0) { + return { + geometry, + applied: false, + holeLoops: [] + } + } + + const nextIndices = [...meshData.indices] + bridgeTriangles.forEach(triangle => nextIndices.push(...triangle)) + replaceGeometryData(geometry, meshData.positions, nextIndices) + + return { + geometry, + applied: true, + holeLoops: getSelectedHoleLoops(geometry, { + selectionMode: 'vertex', + selectedVertexIndices + }) + } +} + +export function bridgeAndFillSelectedHole(geometry, selectedVertexIndices = []) { + const bridgeResult = bridgeSelectedHoleSegments(geometry, selectedVertexIndices) + if (!bridgeResult.applied) { + return { + geometry, + applied: false + } + } + + const reducedLoops = bridgeResult.holeLoops + + if (reducedLoops.length > 0) { + fillHoleLoops(geometry, reducedLoops) + } + + return { + geometry, + applied: true + } } export function getFaceSelectionGeometry(geometry, selectedFaceIndices = []) { - const meshData = geometryToMeshData(geometry) - const positions = [] + if (!geometry?.attributes?.position || !geometry?.index || selectedFaceIndices.length === 0) { + return new THREE.BufferGeometry() + } + + const sourcePositions = geometry.attributes.position.array + const indices = geometry.index.array + const positions = new Float32Array(selectedFaceIndices.length * 9) + let writeOffset = 0 selectedFaceIndices.forEach(faceIndex => { - getFace(meshData, faceIndex).forEach(vertexIndex => { - positions.push( - meshData.positions[vertexIndex * 3], - meshData.positions[vertexIndex * 3 + 1], - meshData.positions[vertexIndex * 3 + 2] - ) - }) + const faceOffset = faceIndex * 3 + + for (let cornerIndex = 0; cornerIndex < 3; cornerIndex += 1) { + const vertexIndex = indices[faceOffset + cornerIndex] * 3 + positions[writeOffset] = sourcePositions[vertexIndex] + positions[writeOffset + 1] = sourcePositions[vertexIndex + 1] + positions[writeOffset + 2] = sourcePositions[vertexIndex + 2] + writeOffset += 3 + } }) const selectionGeometry = new THREE.BufferGeometry() - selectionGeometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3)) + selectionGeometry.setAttribute('position', new THREE.BufferAttribute(positions, 3)) selectionGeometry.computeVertexNormals() return selectionGeometry } @@ -589,11 +1121,18 @@ export function getVertexSelectionPositions(geometry, selectedVertexIndices = [] return [] } - return selectedVertexIndices.flatMap(vertexIndex => [ - positionAttribute.getX(vertexIndex), - positionAttribute.getY(vertexIndex), - positionAttribute.getZ(vertexIndex) - ]) + const sourcePositions = positionAttribute.array + const positions = new Float32Array(selectedVertexIndices.length * 3) + + selectedVertexIndices.forEach((vertexIndex, selectionIndex) => { + const sourceOffset = vertexIndex * 3 + const targetOffset = selectionIndex * 3 + positions[targetOffset] = sourcePositions[sourceOffset] + positions[targetOffset + 1] = sourcePositions[sourceOffset + 1] + positions[targetOffset + 2] = sourcePositions[sourceOffset + 2] + }) + + return positions } export function getClosestVertexIndex(geometry, faceIndex, point) { @@ -611,12 +1150,10 @@ export function getClosestVertexIndex(geometry, faceIndex, point) { let closestDistance = Number.POSITIVE_INFINITY candidates.forEach(vertexIndex => { - const vertex = new THREE.Vector3( - positionAttribute.getX(vertexIndex), - positionAttribute.getY(vertexIndex), - positionAttribute.getZ(vertexIndex) - ) - const distance = vertex.distanceTo(point) + const dx = positionAttribute.getX(vertexIndex) - point.x + const dy = positionAttribute.getY(vertexIndex) - point.y + const dz = positionAttribute.getZ(vertexIndex) - point.z + const distance = dx * dx + dy * dy + dz * dz if (distance < closestDistance) { closestDistance = distance closestVertex = vertexIndex diff --git a/storage.js b/storage.js index e13474f..e2d9f51 100644 --- a/storage.js +++ b/storage.js @@ -34,7 +34,8 @@ const NODE_TYPES = [ { id: 3, name: 'Mesh' }, { id: 4, name: 'Number' }, { id: 5, name: 'Text' }, - { id: 6, name: 'Boolean' } + { id: 6, name: 'Boolean' }, + { id: 7, name: 'Image Compare' } ]; export const DEFAULT_SETTINGS = {