Finish slicing box and UI

This commit is contained in:
Fuhrmann 2025-03-07 10:09:38 +01:00
parent 8227b4141a
commit 213537508c
19 changed files with 965 additions and 1361 deletions

View file

@ -1,36 +1,123 @@
"use client";
import {
Accordion,
Button,
Checkbox,
Label,
TextInput,
ToggleSwitch,
} from "flowbite-react";
import { useContext, useState } from "react";
import { ReactNode, useContext, useRef, useState } from "react";
import {
MapSceneContext,
MapSceneContextType,
} from "../providers/map-scene-provider";
SceneViewContext,
SceneViewContextType,
} from "../providers/scene-view-provider";
import { Mesh, MeshStandardMaterial } from "three";
function Toggle({
title,
onChange,
defaultChecked,
}: {
title: string;
onChange: () => void;
defaultChecked?: boolean;
}) {
return (
<label className="inline-flex items-center cursor-pointer">
<input
type="checkbox"
value=""
className="sr-only peer"
onChange={onChange}
defaultChecked={defaultChecked ? true : false}
/>
<div className="relative w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-blue-600 dark:peer-checked:bg-blue-600"></div>
<span className="ms-3 text-sm font-medium text-gray-900 dark:text-gray-300">
{title}
</span>
</label>
);
}
function Accordion({
children,
title,
}: {
children?: ReactNode;
title: string;
}) {
const [expanded, setExpanded] = useState<boolean>(true);
const accordionBodyRef = useRef<HTMLDivElement>(null);
function handleClick() {
if (!accordionBodyRef.current) return;
accordionBodyRef.current.classList.toggle("hidden");
setExpanded(!expanded);
}
return (
<div>
<h2 id="accordion-collapse-heading-1">
<button
type="button"
className="flex items-center justify-between w-full p-5 font-medium rtl:text-right text-gray-500 border border-b-0 border-gray-200 rounded-t-xl focus:ring-4 focus:ring-gray-200 dark:focus:ring-gray-800 dark:border-gray-700 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-800 gap-3 hover:cursor-pointer"
data-accordion-target="#accordion-collapse-body-1"
aria-expanded={expanded ? "true" : "false"}
aria-controls="accordion-collapse-body-1"
onClick={handleClick}
>
<span>{title}</span>
<svg
data-accordion-icon
className="w-3 h-3 rotate-180 shrink-0"
aria-hidden="true"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 10 6"
>
<path
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M9 5 5 1 1 5"
/>
</svg>
</button>
</h2>
<div
id="accordion-collapse-body-1"
ref={accordionBodyRef}
aria-labelledby="accordion-collapse-heading-1"
>
<div className="p-5 border border-gray-200 dark:border-gray-700 dark:bg-gray-900">
{children}
</div>
</div>
</div>
);
}
export function Form() {
const [enabled, setEnabled] = useState<boolean>(true);
const { mapScene } = useContext(MapSceneContext) as MapSceneContextType;
const { sceneView } = useContext(SceneViewContext) as SceneViewContextType;
function handleChange() {
if (!mapScene) return;
if (!sceneView) return;
mapScene.toggleClippingBox();
setEnabled(!enabled);
sceneView.toggleClippingBox();
}
function handleChangeCG() {
if (!sceneView) return;
sceneView.toggleCoordinateGrid();
}
function handleChangeWireframe() {
if (!sceneView) return;
sceneView.toggleWireFrame();
}
function handleCheckboxChange(name: string) {
if (!mapScene) return;
if (!sceneView) return;
const mesh = mapScene.model.getObjectByName(name);
const mesh = sceneView.model.getObjectByName(name);
if (mesh) {
mesh.visible = !mesh.visible;
}
@ -39,44 +126,52 @@ export function Form() {
return (
<div className="w-full flex flex-col gap-2 overflow-y-auto">
<div className="w-full flex flex-col gap-3 p-4 border border-gray-200 rounded shadow">
<ToggleSwitch
checked={enabled}
label="Toggle Slicing Box"
onChange={handleChange}
<Toggle title="Slicing Box" onChange={handleChange} />
<Toggle
title="Coordinate grid"
onChange={handleChangeCG}
defaultChecked
/>
<Accordion>
<Accordion.Panel>
<Accordion.Title>Layers</Accordion.Title>
<Accordion.Content>
<div className="mt-2">
{mapScene?.model.children.map((child) => {
<Toggle title="Wireframe" onChange={handleChangeWireframe} />
<Accordion title="Layers">
{
<div className="flex flex-col gap-2">
{sceneView?.model.children.map((child) => {
const key = `toggle-visibility-${child.name}`;
const color = `#${(
(child as Mesh).material as MeshStandardMaterial
).color.getHexString()}`;
const visible = (child as Mesh).visible;
return (
<div key={key} className="flex items-center ml-2">
<div
key={key}
className="flex items-center justify-start gap-2.5 border-b border-gray-200 py-1"
>
<span
className="inline-block w-4 h-4"
className="inline-block w-5 h-5 flex-none rounded"
style={{
backgroundColor: color,
}}
></span>
<Checkbox
<input
id={key}
defaultChecked
type="checkbox"
onChange={() => handleCheckboxChange(child.name)}
className="ml-2"
className="hover:cursor-pointer"
defaultChecked={visible ? true : false}
/>
<Label htmlFor={key} className="ml-2">
<label
htmlFor={key}
className="antialiased font-light text-gray-700"
>
{child.name}
</Label>
</label>
</div>
);
})}
</div>
</Accordion.Content>
</Accordion.Panel>
}
</Accordion>
</div>
</div>

View file

@ -1,15 +1,15 @@
"use client";
import { useContext, useEffect, useRef } from "react";
import { MapScene } from "../three/MapScene";
import { SceneView } from "../three/SceneView";
import {
MapSceneContext,
MapSceneContextType,
} from "../providers/map-scene-provider";
SceneViewContext,
SceneViewContextType,
} from "../providers/scene-view-provider";
export function Map() {
const divRef = useRef<HTMLDivElement>(null);
const { setMapScene } = useContext(MapSceneContext) as MapSceneContextType;
const { setSceneView } = useContext(SceneViewContext) as SceneViewContextType;
useEffect(() => {
let ignore = false;
@ -17,9 +17,9 @@ export function Map() {
async function loadScene() {
if (divRef.current) {
const _mapScene = await MapScene.create(divRef.current, "20");
if (_mapScene) {
setMapScene(_mapScene);
const _sceneView = await SceneView.create(divRef.current, "20");
if (_sceneView) {
setSceneView(_sceneView);
}
}
}

View file

@ -1,6 +1,4 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@import "tailwindcss";
:root {
--background: #ffffff;

View file

@ -1,21 +1,21 @@
import { Map } from "./components/Map";
import { Form } from "./components/Form";
import { MapSceneProvider } from "./providers/map-scene-provider";
import { SceneViewProvider } from "./providers/scene-view-provider";
export default function Home() {
return (
<div className="w-screen h-screen">
<main className="h-screen">
<MapSceneProvider>
<SceneViewProvider>
<div className="flex h-full">
<div className="flex-1">
<Map></Map>
</div>
<div className="w-[480px] p-4 flex flex-col items-center">
<div className="w-[480px] p-4 flex flex-col items-center border-l border-gray-200">
<Form></Form>
</div>
</div>
</MapSceneProvider>
</SceneViewProvider>
</main>
</div>
);

View file

@ -1,36 +0,0 @@
"use client";
import {
createContext,
Dispatch,
ReactNode,
SetStateAction,
useState,
} from "react";
import { MapScene } from "../three/MapScene";
// Declare MapScene context
export type MapSceneContextType = {
mapScene: MapScene | null;
setMapScene: Dispatch<SetStateAction<MapScene | null>>;
};
// Context for MapScene
export const MapSceneContext = createContext<MapSceneContextType | null>(null);
// Context provider for MapScene
export const MapSceneProvider = ({ children }: { children: ReactNode }) => {
const [mapScene, setMapScene] = useState<MapScene | null>(null);
return (
<MapSceneContext.Provider
value={{
mapScene: mapScene,
setMapScene: setMapScene,
}}
>
{children}
</MapSceneContext.Provider>
);
};

View file

@ -0,0 +1,38 @@
"use client";
import {
createContext,
Dispatch,
ReactNode,
SetStateAction,
useState,
} from "react";
import { SceneView } from "../three/SceneView";
// Declare SceneView context
export type SceneViewContextType = {
sceneView: SceneView | null;
setSceneView: Dispatch<SetStateAction<SceneView | null>>;
};
// Context for SceneView
export const SceneViewContext = createContext<SceneViewContextType | null>(
null
);
// Context provider for SceneView
export const SceneViewProvider = ({ children }: { children: ReactNode }) => {
const [sceneView, setSceneView] = useState<SceneView | null>(null);
return (
<SceneViewContext.Provider
value={{
sceneView: sceneView,
setSceneView: setSceneView,
}}
>
{children}
</SceneViewContext.Provider>
);
};

View file

@ -1,13 +1,13 @@
import { AxesHelper, Group, Scene } from "three";
import { AxesHelper, Group, Mesh, MeshStandardMaterial, Scene } from "three";
import { buildMeshes } from "./utils/build-meshes";
import { Extent, buildScene } from "./utils/build-scene";
import { getMetadata } from "./utils/utils";
import { MODEL_ID, SERVICE_URL } from "./config";
import { buildClippingplanes } from "./utils/build-clipping-planes";
import { buildGrid } from "./utils/build-grid";
import { buildCoordinateGrid } from "./utils/build-coordinate-grid";
import { DragControls } from "three/examples/jsm/Addons.js";
export class MapScene {
export class SceneView {
private _scene: Scene;
private _dragControls: DragControls;
private _model: Group;
@ -20,7 +20,7 @@ export class MapScene {
static async create(container: HTMLElement, modelId: string) {
const { scene, model, dragControls } = await init(container, modelId);
return new MapScene(scene, model, dragControls);
return new SceneView(scene, model, dragControls);
}
get scene() {
@ -51,6 +51,21 @@ export class MapScene {
mesh.visible = !mesh.visible;
}
}
toggleCoordinateGrid() {
const group = this._scene.getObjectByName("coordinate-grid");
if (group) {
group.visible = !group.visible;
}
}
toggleWireFrame() {
const model = this._model;
model.children.forEach((child) => {
const material = (child as Mesh).material as MeshStandardMaterial;
material.wireframe = !material.wireframe;
});
}
}
async function init(container: HTMLElement, modelId = MODEL_ID) {
@ -92,11 +107,11 @@ async function init(container: HTMLElement, modelId = MODEL_ID) {
}
// Add a coordinate grid to the scene
const { gridHelper, annotations } = buildGrid(extent);
const { gridHelper, annotations } = buildCoordinateGrid(extent);
const annotationsGroup = new Group();
annotationsGroup.name = "coordinate-grid";
annotationsGroup.add(...annotations);
scene.add(gridHelper, annotationsGroup);
annotationsGroup.add(...annotations, gridHelper);
scene.add(annotationsGroup);
//const axesHelper = new AxesHelper(5);
//scene.add(axesHelper);

View file

@ -166,6 +166,7 @@ export function buildClippingplanes(
const clippingBox = new Group();
clippingBox.add(planeMeshGroup, edgeMeshGroup);
clippingBox.name = "clipping-box";
clippingBox.visible = false;
scene.add(clippingBox);
// Enable DragControls for the clipping planes
@ -175,18 +176,11 @@ export function buildClippingplanes(
renderer.domElement
);
dragControls.addEventListener("dragstart", (event) => {
const object = event.object as PlaneMesh;
dragControls.enabled = false;
dragControls.addEventListener("dragstart", () => {
// Disable OrbitControls when dragging starts
orbitControls.enabled = false;
// Remove existing cap meshes
const capMeshGroupName = `cap-mesh-group-${object.name}`;
let capMeshGroup = scene.getObjectByName(capMeshGroupName);
while (capMeshGroup) {
scene.remove(capMeshGroup);
capMeshGroup = scene.getObjectByName(capMeshGroupName);
}
});
dragControls.addEventListener("dragend", () => {
@ -468,6 +462,8 @@ function generateCapMeshes(
// Iterate over the list of geologic meshes
for (let mesh of meshes) {
// Slice visible meshes only
if (mesh.visible) {
const position = mesh.geometry.attributes.position.array;
const indices = mesh.geometry.index ? mesh.geometry.index.array : null;
const edges: Array<[Vector3, Vector3]> = [];
@ -481,9 +477,21 @@ function generateCapMeshes(
const i2 = indices ? indices[i + 1] * 3 : (i + 1) * 3;
const i3 = indices ? indices[i + 2] * 3 : (i + 2) * 3;
const v1 = new Vector3(position[i1], position[i1 + 1], position[i1 + 2]);
const v2 = new Vector3(position[i2], position[i2 + 1], position[i2 + 2]);
const v3 = new Vector3(position[i3], position[i3 + 1], position[i3 + 2]);
const v1 = new Vector3(
position[i1],
position[i1 + 1],
position[i1 + 2]
);
const v2 = new Vector3(
position[i2],
position[i2 + 1],
position[i2 + 2]
);
const v3 = new Vector3(
position[i3],
position[i3 + 1],
position[i3 + 2]
);
// Check if the triangle is cut by the plane
const d1 = plane.distanceToPoint(v1);
@ -506,7 +514,9 @@ function generateCapMeshes(
const polygons: Vector3[][] = buildPolygons(edges);
// Clip cap surfaces with clipping planes
const clippingPlanes = planes.filter((p) => !p.normal.equals(plane.normal));
const clippingPlanes = planes.filter(
(p) => !p.normal.equals(plane.normal)
);
const offset = orientation === Orientation.Z ? 1 : -1;
const material = new MeshStandardMaterial({
@ -540,6 +550,7 @@ function generateCapMeshes(
capMeshes.push(...localMeshes);
}
}
return capMeshes;
}

View file

@ -13,7 +13,7 @@ enum Orientation {
Vertical,
}
export function buildGrid(extent: Extent) {
export function buildCoordinateGrid(extent: Extent) {
const center = getCenter3D(extent);
// Calculate the width and height of the grid
const gridWidth = extent.xmax - extent.xmin;
@ -26,10 +26,10 @@ export function buildGrid(extent: Extent) {
const gridHelper = new GridHelper(Math.max(gridWidth, gridHeight), divisions);
// Position the grid in the scene to match the given extent
gridHelper.position.set(center.x, center.y, 0); // Center the grid at the midpoint
gridHelper.position.set(center.x, center.y, 0);
// Rotate the grid if needed to align with the world coordinates
gridHelper.rotation.x = Math.PI / 2; // Rotate to align with the XY plane
// Rotate the grid to align with the XY-plane
gridHelper.rotation.x = Math.PI / 2;
// Retrieve the geometry of the grid helper
const geometry = gridHelper.geometry;

View file

@ -1,29 +0,0 @@
import { AmbientLight, DirectionalLight, Scene } from "three";
const DEG2RAD = Math.PI / 180;
export function buildDefaultLights(scene: Scene) {
// ambient light
scene.add(new AmbientLight(0x999999));
// directional lights
const opt = {
azimuth: 220,
altitude: 45,
};
const lambda = (90 - opt.azimuth) * DEG2RAD;
const phi = opt.altitude * DEG2RAD;
const x = Math.cos(phi) * Math.cos(lambda);
const y = Math.cos(phi) * Math.sin(lambda);
const z = Math.sin(phi);
const light1 = new DirectionalLight(0xffffff, 0.5);
light1.position.set(x, y, z);
scene.add(light1);
// thin light from the opposite direction
const light2 = new DirectionalLight(0xffffff, 0.1);
light2.position.set(-x, -y, -z);
scene.add(light2);
}

View file

@ -6,8 +6,7 @@ import {
MeshStandardMaterial,
} from "three";
import { fetchTriangleIndices } from "./fetch-triangle-indices";
import { fetchVertices } from "./fetch-vertices";
import { fetchVertices, fetchTriangleIndices } from "./utils";
import { TRIANGLE_INDICES_URL, VERTICES_URL } from "../config";
interface MappedFeature {
@ -22,6 +21,9 @@ export async function buildMeshes(mappedFeatures: MappedFeature[]) {
for (let i = 0; i < mappedFeatures.length; i++) {
const layerData = mappedFeatures[i];
const mesh = await buildMesh(layerData);
if (layerData.name === "Topography") {
mesh.visible = false;
}
meshes.push(mesh);
}

View file

@ -1,9 +1,42 @@
import { Color, PerspectiveCamera, Scene, Vector3, WebGLRenderer } from "three";
import {
PerspectiveCamera,
Scene,
WebGLRenderer,
AmbientLight,
DirectionalLight,
} from "three";
import { buildDefaultLights } from "./build-default-lights";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { getCenter3D, getMaxSize } from "./utils";
const DEG2RAD = Math.PI / 180;
function buildDefaultLights() {
// Ambient light
scene.add(new AmbientLight(0xaaaaaa));
// Directional lights
const opt = {
azimuth: 220,
altitude: 45,
};
const lambda = (90 - opt.azimuth) * DEG2RAD;
const phi = opt.altitude * DEG2RAD;
const x = Math.cos(phi) * Math.cos(lambda);
const y = Math.cos(phi) * Math.sin(lambda);
const z = Math.sin(phi);
const light1 = new DirectionalLight(0xffffff, 0.5);
light1.position.set(x, y, z);
scene.add(light1);
// Thin light from the opposite direction
const light2 = new DirectionalLight(0xffffff, 0.1);
light2.position.set(-x, -y, -z);
return light2;
}
export interface Extent {
xmin: number;
ymin: number;
@ -34,6 +67,7 @@ export function buildScene(container: HTMLElement, extent: Extent) {
camera.position.set(center.x, center.y - 125000, extent.zmax + 100000);
camera.lookAt(center);
// Initialize the renderer
renderer = new WebGLRenderer({
alpha: true,
logarithmicDepthBuffer: true,
@ -43,6 +77,8 @@ export function buildScene(container: HTMLElement, extent: Extent) {
renderer.setSize(width, height);
renderer.localClippingEnabled = true;
renderer.setAnimationLoop(animate);
// Handle window resize event to adapt the aspect ratio
window.addEventListener("resize", () => onWindowResize(container));
container.appendChild(renderer.domElement);
@ -55,16 +91,18 @@ export function buildScene(container: HTMLElement, extent: Extent) {
// Scene will hold all our elements such as objects, cameras and lights
scene = new Scene();
scene.background = new Color(0xdddddd);
buildDefaultLights(scene);
// Add lights to the scene
const lights = buildDefaultLights();
lights.name = "lights";
scene.add(lights);
return { renderer, scene, camera, controls };
}
function onWindowResize(container: HTMLElement) {
// Update the camera's aspect ratio and the renderer's size to reflect
// the new screen dimensions upon a browser window resize.
// the new screen dimensions upon a browser window resize
camera.aspect = container.clientWidth / container.clientHeight;
camera.updateProjectionMatrix();
renderer.setSize(container.clientWidth, container.clientHeight);

View file

@ -1,8 +0,0 @@
import { request } from "./request";
import { unpackEdges } from "./parsers";
export async function fetchTriangleIndices(edgeUrl: string, geomId: string) {
const url = edgeUrl + geomId;
const buffer = await request(url);
return unpackEdges(buffer);
}

View file

@ -1,8 +0,0 @@
import { unpackVertices } from "./parsers";
import { request } from "./request";
export async function fetchVertices(pointUrl: string, geomId: string) {
const url = pointUrl + geomId;
const buffer = await request(url);
return unpackVertices(buffer);
}

View file

@ -1,8 +0,0 @@
export async function request(url: string) {
const response = await fetch(url);
if (response.ok) {
return response.arrayBuffer();
} else {
throw new Error("HTTP error status: " + response.status);
}
}

View file

@ -1,5 +1,6 @@
import { Vector3 } from "three";
import { Extent } from "./build-scene";
import { unpackEdges, unpackVertices } from "./parsers";
export function getMaxSize(extent: Extent) {
return Math.max(
@ -32,3 +33,24 @@ export async function getMetadata(serviceUrl: string) {
throw new Error("HTTP error status: " + response.status);
}
}
export async function request(url: string) {
const response = await fetch(url);
if (response.ok) {
return response.arrayBuffer();
} else {
throw new Error("HTTP error status: " + response.status);
}
}
export async function fetchTriangleIndices(edgeUrl: string, geomId: string) {
const url = edgeUrl + geomId;
const buffer = await request(url);
return unpackEdges(buffer);
}
export async function fetchVertices(pointUrl: string, geomId: string) {
const url = pointUrl + geomId;
const buffer = await request(url);
return unpackVertices(buffer);
}

1670
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -10,24 +10,24 @@
},
"dependencies": {
"earcut": "^3.0.1",
"flowbite-react": "^0.10.2",
"next": "15.1.7",
"next": "15.2.1",
"proj4": "^2.15.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"three": "^0.173.0"
"three": "^0.174.0"
},
"devDependencies": {
"@eslint/eslintrc": "^3",
"@tailwindcss/postcss": "^4.0.11",
"@types/earcut": "^3.0.0",
"@types/node": "^20",
"@types/node": "^22",
"@types/react": "^19",
"@types/react-dom": "^19",
"@types/three": "^0.173.0",
"@types/three": "^0.174.0",
"eslint": "^9",
"eslint-config-next": "15.1.7",
"postcss": "^8",
"tailwindcss": "^3.4.1",
"eslint-config-next": "15.2.1",
"postcss": "^8.5.3",
"tailwindcss": "^4.0.11",
"typescript": "^5"
}
}

View file

@ -1,8 +1,6 @@
/** @type {import('postcss-load-config').Config} */
const config = {
/** @type {import('tailwindcss').Config} */
export default {
plugins: {
tailwindcss: {},
"@tailwindcss/postcss": {},
},
};
export default config;