diff --git a/.github/workflows/matterviz-gui.yml b/.github/workflows/matterviz-gui.yml index b5415dd0..47530ee5 100644 --- a/.github/workflows/matterviz-gui.yml +++ b/.github/workflows/matterviz-gui.yml @@ -39,7 +39,6 @@ on: - tests/test_matterviz_build_names.py - tests/test_matterviz_mapped_surfaces.py - tests/test_matterviz_plot_adapter.py - - tests/test_matterviz_topology_vendor.py - tests/test_macos_app_bundle.py - tools/macos/** - tests/matterviz_plot_capture_harness.f90 @@ -95,10 +94,11 @@ jobs: pnpm check VITE_MATTERVIZ_PRERELEASE_UPDATER=1 pnpm build - - name: Test frequency viewer interactions + - name: Test native isosurface finishes and frequency viewer interactions working-directory: frontend/matterviz-viewer run: | pnpm exec playwright install --with-deps chromium + pnpm test:scene-export pnpm test:frequency - name: Upload frequency viewer failure artifacts @@ -163,7 +163,7 @@ jobs: bash tests/c/run_matterviz_stream_test.sh - name: Test MatterViz build contract - run: python3 -m unittest -v tests/test_gui_session_paths.py tests/test_matterviz_build_names.py tests/test_matterviz_mapped_surfaces.py tests/test_matterviz_plot_adapter.py tests/test_matterviz_topology_vendor.py tests/test_macos_app_bundle.py + run: python3 -m unittest -v tests/test_gui_session_paths.py tests/test_matterviz_build_names.py tests/test_matterviz_mapped_surfaces.py tests/test_matterviz_plot_adapter.py tests/test_macos_app_bundle.py - name: Build Multiwfn with MatterViz frontend run: | diff --git a/docs/frequency-viewer.md b/docs/frequency-viewer.md index c8aec690..e85c269e 100644 --- a/docs/frequency-viewer.md +++ b/docs/frequency-viewer.md @@ -67,15 +67,7 @@ core sources and the pinned BaneWfn source are unchanged; noGUI dependencies are unchanged. Existing Multiwfn frequency calculations and spectrum plotting continue to own their scientific behavior. -The retained MatterViz package already exports `Trajectory`; it does not -export `PhononModeExplorer`. Upstream at -[`59f6b563`](https://github.com/janosh/matterviz/blob/59f6b563527877bbc2cee66affb96a215cc8e000/src/lib/spectral/phonon-modes.ts) -still requires a real-space lattice and divides phonopy eigenvectors by -`sqrt(mass)`. Feeding molecular Cartesian data into that API would be incorrect. -This PR therefore uses the existing native trajectory renderer with a bounded -data adapter. A future MatterViz molecular-mode interface can replace that -adapter without changing the importer or application host. This is not a -claim that the upstream phonon explorer supports molecules today. +The panel passes a lazy frame source to the native MatterViz `Trajectory` component. The adapter uses molecular Cartesian displacements and preserves their relative amplitudes. Playback and frame selection use the upstream controls. Spectrum broadening, frequency computation, new quantum-output parsers, CP2K/xTB support and video export are outside this rendering PR. @@ -89,30 +81,3 @@ renderer in Chromium. The test covers paused startup, native playback and scrubbing, mode changes, amplitude validation, camera interaction, import failure recovery and closing/reopening the viewer. Python is only needed to regenerate the documented cclib fixtures. - -## Camera compatibility patch - -The retained renderer clears `camera_target` and `camera_zoom` on every new -structure object. A trajectory provides a new object each frame, so native -zoom was lost during playback and mode switching. The focused `r25.freq1` -backport adds upstream's `Structure.structure_series_key` contract and shares -it with `StructureViewport` to retain the native reset baseline. This viewer -passes its dataset as the key; changing files mounts a fresh scene, while -changing modes/amplitude preserves camera position, zoom and reset state. - -Source design: MatterViz -[`59f6b563`, Structure.svelte](https://github.com/janosh/matterviz/blob/59f6b563527877bbc2cee66affb96a215cc8e000/src/lib/structure/Structure.svelte) -and `StructureViewport.svelte`. This is a small compatibility adaptation to -the retained renderer, not a wholesale cherry-pick of the newer session system. -Callers that omit the key retain existing behavior. A caller must use a new key -when topology changes; coordinate-only frames may share one. - -Apply `vendor/patches/matterviz-0.4.2-multiwfn.d8719d12.r25.freq1.patch` with -`patch -p1` inside the extracted `r25.reps2` package. Only the two Svelte files, -their declarations and the package version change. The Python vendor replay -test verifies byte-identical contents against the new archive and checks the -complete changed-file allowlist. SHA-256 of `r25.freq1.tgz`: - -```text -0f24494f31d94479a78c741958a5929cbc68efcc7af63db31f8603ecd70bf9fa -``` diff --git a/docs/representation-workbench.md b/docs/representation-workbench.md index b3bb8607..8fe72073 100644 --- a/docs/representation-workbench.md +++ b/docs/representation-workbench.md @@ -1,5 +1,7 @@ # Representation workbench +This document describes the former customized MatterViz 0.4.2 viewer. The current viewer uses the upstream structure and surface controls. [Current viewer documentation](../frontend/matterviz-viewer/README.md) + The workbench uses VMD's representation model: a list of independently visible representations, with one editor for the selected representation. Each Rep owns its data source, drawing method, material, and periodic display. Camera, lighting, diff --git a/frontend/matterviz-viewer/README.md b/frontend/matterviz-viewer/README.md index c4ac0304..80ddc994 100644 --- a/frontend/matterviz-viewer/README.md +++ b/frontend/matterviz-viewer/README.md @@ -11,86 +11,11 @@ frequency results exported as cclib CJSON. It uses MatterViz's native trajectory renderer and starts paused. See [frequency viewing](../../docs/frequency-viewer.md) for conversion, supported inputs and displacement conventions. -The frontend consumes `vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.freq1.tgz`. -The [frequency camera patch](../../docs/frequency-viewer.md#camera-compatibility-patch) -extends `r25.reps2` with the upstream series-identity contract. Reps2's -reviewable color patch extends the retained `r25.reps1` archive, preserving the -reviewed topology, measurement, material, parser and sampling fixes. Reps render -geometry in the host scene without adding cameras or lights. Their atoms and -bonds share the standard matte/glossy/PBR/unlit material pool, with gradient bond -colors, opacity, rim shading and local clipping. -Editable color scales use shared sRGB control points for surface coloring and -the legend; color-only edits reuse the extracted geometry. The renderer reports -its actual surface-fitted color range so automatic legend ticks remain accurate. - -See [the representation workbench](../../docs/representation-workbench.md) for -controls, migration, resource limits and browser acceptance coverage. - -The topology extension exposes shared scene snippets, `topology_view` and -`surface_view` masks, and shares native scene/lattice control dictionaries with -the parent so camera snapshots cannot reset auto-rotation. Topology shows atoms -and hides ordinary bonds and scalar surfaces; quantitative-surface view hides -scalar surfaces while keeping chemical bonds. Rendering resources stay mounted, -but hidden bond hit targets and their HTML menu unmount. Atom/label right-clicks -cannot target hidden bonds, previous menus/hover clear when views change, and -atom picking remains available even when the ordinary view's atom toggle is off. -All topology and quantitative-surface analysis logic stays in the frontend and -GUI adapters; the vendor adds no scientific calculation or geometry extraction. - -The material extension adds bounded rim shading and angle-dependent transparency -to lit finishes, using Three r185's unexpanded output include and preserving -zero/fully opaque alpha endpoints. Saved-camera restoration also reconciles -orientation after declarative pose setters, while identical live Arcball -feedback preserves the current quaternion. Worker buffer returns support -environments without SharedArrayBuffer. - -Legacy Trans Flag coloring uses negative pink `#f5a9b8`, physical-zero white and -positive blue `#5bcefa`. Its vertex colors and colorbars share those semantics for -asymmetric, one-sided and zero-width ranges, with an odd-sized LUT preserving -exact white at zero. Saved ranges migrate to editable points with those colors -intact. The fresh pink/white/blue preset places its points at 0%, 50% and 100%; -subsequent range changes keep their percentage positions fixed. Explicit ESP -layers use this palette by default. Typed Worker geometry recomputes area-weighted normals from -its final Cartesian vertices, reusing the allocated normal buffer. This matches -the legacy path for rotated, anisotropic and nonorthogonal cells. Unlit and -wireframe surfaces bypass tone mapping so their colors agree with the legend; -lit finishes retain the renderer's tone mapping and transparency. - -The retained lineage is r25 → workbench1 → workbench2 → upstream1 → reps1 → reps2. -Earlier reviewed archives and patches remain reproducible bases. The current -reps2 archive SHA-256 is `cef5d1e2c97e6c65041ba3b0a50d94b41acbd7705d85a8d3cd4b7ed7218632ec`; -`package.json` and `pnpm-lock.yaml` pin its path and integrity. - -To reproduce the current package (Node.js 24 and npm): +The viewer uses the unmodified `main` branch of [janosh/matterviz](https://github.com/janosh/matterviz). The pnpm lockfile records the exact commit for reproducible desktop builds. To take a later upstream revision, run `pnpm update matterviz` in this directory and commit the refreshed lockfile after testing. -```bash -workbench_tmpdir="$(mktemp -d)" -tar -xzf vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.reps1.tgz -C "$workbench_tmpdir" -patch -d "$workbench_tmpdir/package" -p1 < vendor/patches/matterviz-0.4.2-multiwfn.d8719d12.r25.reps2.patch -npm pack --ignore-scripts --pack-destination vendor "$workbench_tmpdir/package" -sha256sum vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.reps2.tgz -``` +Open **Structure controls** and select an isosurface finish. The native WebGPU viewer provides Satin, Translucent shell, Chalk and Unlit. Satin uses shell shading on translucent single-color layers. Set an orbital layer's opacity to 1 to see its opaque satin finish. The structure viewer also owns the isosurface layers, atom editing, measurements, camera and volume slices. Old Reps display snapshots and custom material settings belonged to the retired workbench. Native JSON with a ghost species such as `Bq` follows upstream's unsupported-species diagnostics. -The checksum identifies the retained archive. To verify a repack across npm -versions, `tests/test_matterviz_topology_vendor.py` compares every extracted -package file against an independent patch replay, avoiding tar metadata -differences. It also checks that both reviewed vendor branches remain present. - -`pnpm test:color-scale` checks editable preset/custom stops against real WebGL -surface buffers and pixels, legend ranges, independent copies, saved settings, -validation and bilingual/narrow-screen controls. Like the other representation -browser scripts, it uses the running local session preview and accepts -`PLAYWRIGHT_MODULE`, `PLAYWRIGHT_CHROMIUM_EXECUTABLE`, `PREVIEW_URL` and `ARTIFACT_DIR`. - -`pnpm test:topology-picking` runs the installed scene in Chromium with real Three.js -raycasting and Threlte event registration. It requires Playwright and its Chromium -browser. An external Playwright install can be selected with `PLAYWRIGHT_MODULE` -(the absolute path to its `index.mjs`); `PLAYWRIGHT_CHROMIUM_EXECUTABLE` optionally -selects an existing Chromium executable. `KEEP_BROWSER_FIXTURE=1` retains the -temporary fixture and JSON evidence. The test checks hidden-bond deletion and -context menus, atom/partial-occupancy/label interaction, and retained bond geometry. -A real typed-grid density surface also verifies both display masks, preserving -its mesh, geometry and material while atoms and chemical bonds follow their masks. +Multiwfn loads Cube files and binary fields into the native volume list. Density surfaces refer to their coloring field by ID. A declared custom gradient uses the closest native named palette, preserving its direction and physical range. ESP potential values declared in kcal/mol are converted to atomic units before mapping. ## AIM topology workbench @@ -133,19 +58,12 @@ Float64 x/y/z arrays in Bohr, CPs first followed by complete path polylines. Dataset lifetime is independent of 2D plots; replacement releases only old topology arrays. Refreshing the page restores the latest result without computing. -The scene extension renders instanced CP spheres and batched thick path segments -in the molecule's scene coordinate system. Periodic integration steps are -unwrapped, with endpoint CP images retaining the original IDs. The topology mask -hides scalar surfaces and ordinary bonds without unmounting or extracting them. -Display controls and object details are outside the canvas; CSV/JSON export keeps -all raw coordinates, while PNG uses the shared scene. Display settings are saved -separately in the existing workbench state. Changing the underlying geometry -invalidates cached topology and in-flight results. +The analysis view renders critical points and paths in their Cartesian coordinates. Periodic paths retain their original CP IDs. CSV and JSON contain the raw data, and PNG captures the displayed analysis. Changing the underlying geometry invalidates cached and in-flight analysis results. Regression commands from the repository root: ```bash -python3 -m unittest tests/test_matterviz_topology.py tests/test_matterviz_topology_vendor.py +python3 -m unittest tests/test_matterviz_topology.py MULTIWFN_TOPOLOGY_FIXTURE=/path/to/input.fchk python3 -m unittest tests/test_matterviz_topology.py ``` @@ -209,7 +127,7 @@ Snapshots validate references, finite values and a 256 MiB budget, never modify the original arrays, and release their temporary buffers after publication. The renderer orients a copy of triangle winding for consistent normals; original connectivity, coordinates and scalar values remain intact in CSV/JSON exports. -PNG uses the shared 3D scene. Local display controls never invoke marching cubes, +PNG captures the analysis view. Local display controls never invoke marching cubes, an extrema Worker or another backend calculation. Changing structures clears the result; orbitals/ESP temporarily replace its view, and Tools reopens it from memory. Atom/fragment decompositions, surface basins and fingerprint analysis are not @@ -239,7 +157,8 @@ scope of this change. Node.js 24.11 or newer and pnpm 11 are recommended. ```bash -pnpm install +pnpm install --frozen-lockfile +pnpm test pnpm check pnpm build ``` @@ -260,87 +179,11 @@ The workbench keeps frontend and backend operation messages in an in-app log pan use therefore does not depend on terminal output, while calculation failures remain available for copying into bug reports. -The Multiwfn integration currently preserves independent volume layers when dynamic orbitals or -ESP data are calculated. The layer panel controls visibility, isovalue, opacity, deletion, and -strict-grid cross-coloring by another loaded volume. When the manifest exposes bond-analysis -capabilities, select two bonded atoms with MatterViz's measurement tool and right-click either -atom or their visible bond to choose a bond-order calculation. The toolbar remains available for -any valid two-atom calculation, including pairs without a rendered bond. Ordered measurement mode -uses two sites for distance, three for bond angle, and four for signed dihedral angle. - -ESP-colored density surfaces receive a robust symmetric color range, a draggable kcal/mol/e legend, and an -on-demand bounded extrema table. The current MatterViz renderer does not expose a stable API for -arbitrary 3D extrema markers, so extrema coordinates are listed rather than drawn in the scene. -Explicit ESP layers default to pink/white/blue with white at zero. The legend follows -the selected layer palette and manual range, including asymmetric limits. -Surfaces offers Matte, Soft gloss, Satin and Unlit color finishes, with bounded -rim, opacity and shading refinements. Finishes preserve scientific isovalues and -layer colors; periodic boundary padding is under Cell. These settings are saved -with the workbench state. - -### Studio lighting and language selection - -Structure > Lighting preset offers **Standard lighting** and **Studio lighting** -(中文:标准布光 / 影棚布光). Studio lighting is a MatterViz lighting preset, -using hemisphere ambient light, a camera-following key, warm fill, and cool rim. -It disables tone mapping. Standard lighting uses neutral lights and AgX tone mapping. -Reset restores the four light intensities for the selected preset. -The historical `tmim` identifier remains in display snapshots for compatibility. - -Structure > Finish preset offers Balanced, Goodsell, Edgy, Glass, Metallic, and -Matte. Balanced replaces the display name Current; its saved ID remains `current`. -An untouched renderer material shows Renderer default. Atom finish and lighting -are independent controls. These atom presets apply outline parameters that were -inactive in the historical source, so they are not exact recreations of that viewer. - -The toolbar **中文 / EN** button switches Multiwfn-owned controls immediately, -without remounting the scene or changing its camera, scientific data, or materials. -Language is saved in browser localStorage (`multiwfn-ui-language`); the first visit -follows the browser language (Chinese for `zh`, English otherwise). If storage is -unavailable, switching still works for the current page. UI language is independent -of scientific/display exports. User labels, scientific identifiers, and raw backend -logs retain their original text. MatterViz's native embedded controls retain their -upstream language. - -The Surfaces control keeps the four primary finishes above and provides the -legacy MaterialPanel combinations in a dropdown: Diffuse, Goodsell, Edgy, -EdgyShiny, AOShiny, AOChalky, Glass1, GlassBubble, EdgyGlass, BrushedMetal, -Metallic, and PBR. Matte and Unlit are reused from the primary controls. Legacy -names are visual material recipes; names containing AO do not add an ambient -occlusion pass. Transparency is implemented as surface alpha, not physical -refraction. All values are saved and restored with the workbench state, but -rendering is not guaranteed to be pixel-identical across browser or GPU -implementations. - -Save > Save display settings writes a versioned JSON snapshot of layer, periodic, isosurface-material, -lighting, atom-style, and camera state. The same snapshot can be restored with Save > Restore display settings or a `state=` URL query; -the browser and WebView launchers also accept `--state ` and expose only that selected file -through a fixed session route. - -For periodic sessions, manifest cell vectors are injected into structures that would otherwise be -plain molecules (for example XYZ files), so MatterViz can render the cell, boundary atoms, periodic -bonds, and atom supercells. Fractional surface ranges remain independent from the integer atom -supercell. The 2D Slice panel samples any loaded cube on XY/XZ/YZ or custom Miller-index planes and -renders the result on a resizable canvas with selectable color and value ranges. +The orbital panel selects cached orbitals or requests a new grid from Multiwfn. **Tools** exposes ESP, AIM and bond-order calculations when supported by the session. For bond order, select two atoms in the native measurement tool, then choose the method in **Tools**. A visible density surface explicitly colored by its ESP field also enables the approximate-extrema table. ## Unified result workbench -Interactive native 2D plots and the 3D scene now share the result selector, operation log, -Save menu, and Return action. View holds camera steps, axes, inspector, orbitals, layers, -and volume slices; Tools holds backend calculations. Missing ESP capability disables its -calculation button. Sidebars collapse on narrow screens instead of compressing the canvas. -Switching results retains the mounted 3D renderer, camera, selected atoms, and surfaces; -spin pauses while another result is active and resumes on return. - -Backend calculations have their own status row and do not set the renderer's -structure-loading flag or unmount its canvas. Geometry measurements and bond-order -results occupy a scrollable strip outside the 3D viewport; measurement lines and -selection markers remain in the scene. Distances (including PBC/direct values), -ordered angles, and signed dihedrals use the same MatterViz geometry helpers as the -scene. Each bond-order result can be dismissed independently. -The orbital rail includes declared closed-shell HOMO/LUMO shortcuts and centers -its list on the initial frontier pair, or the current orbital when reopened. -This positioning does not scroll the page or request new orbital data. +Interactive 2D plots and the 3D scene share the result selector, operation log, Save menu and Return action. Switching to a plot keeps the structure viewport mounted. The orbital list includes HOMO/LUMO shortcuts for closed-shell sessions. Open plot accepts rectangular numeric `.txt`/`.dat`/`.csv` tables (first column X, remaining columns Y), native v1 plot JSON, and self-contained plot documents. Fortran @@ -395,33 +238,6 @@ produces `Multiwfn_MatterVizGUI`. MatterViz resources do not include the legacy MatterViz is distributed under the MIT license. Multiwfn remains under its original license. -## Workbench UI preview - -The Multiwfn toolbar and inspector now use local shadcn-svelte components: -Button, Popover, Select, Tabs, Slider and Tooltip. The structure renderer remains -MatterViz. Scene settings, original material presets, result selection and -analysis availability still use the existing callbacks and workbench state. -The UI source and local adaptations are documented in -`src/lib/components/ui/README.md`. - -Use the normal `pnpm dev` command with a session manifest for local development. -Browser acceptance against a running preview containing the two density/ESP -fixture volumes is available as: - -```bash -PLAYWRIGHT_MODULE=/path/to/playwright/index.mjs \ -PLAYWRIGHT_CHROMIUM_EXECUTABLE=/path/to/chromium \ -PREVIEW_URL=http://127.0.0.1:5197/ \ -node tests/browser/workbench-ui.mjs -``` - -This checks keyboard navigation, popover dismissal and focus return, all four -lighting controls, material choices, display-setting download/restore, volume -visibility, backend-unavailability help, the single canvas lifecycle and a -600 px viewport. The supplied molecule preview has no calculation backend; -analysis controls retain their real unavailable state. - - ## Local session preview Provide an existing session's data under `session/` in a separate public directory. @@ -435,16 +251,4 @@ PREVIEW_PUBLIC_DIR=/path/to/preview/public pnpm preview:session # Add ?manifest=/session/surface-manifest.json for another manifest. ``` -`pnpm test:representations` checks the molecule/density/ESP fixture in Chromium. -Set `PREVIEW_URL` to its manifest URL, `PLAYWRIGHT_MODULE` to an external Playwright -`index.mjs`, and optionally `PLAYWRIGHT_CHROMIUM_EXECUTABLE`. `ARTIFACT_DIR` controls -where it saves screenshots, portable states and verification JSON. The fixture -expects two compatible grids named Density and ESP and at least 32 structure sites. -`workbench-ui.mjs` and `workbench-language.mjs` additionally cover the retained -advanced inspector. -`pnpm test:scene-export` checks downloaded PNG pixels for white, chosen-color and -transparent backgrounds, translucent materials, bilingual controls and unchanged -camera/scene state, using the same environment variables and surface fixture. -`pnpm test:rep-color` checks diffuse gain and saturation against actual WebGL -pixels for atoms, bonds, mapped surfaces and wireframes, including settings -round-trip and unchanged alpha/camera state. +After building, run `pnpm exec playwright install chromium`, `pnpm test:scene-export` and `pnpm test:frequency`. The finish test opens an orbital and a mapped ESP surface, selects each native finish, downloads the PNGs, and checks their pixels. The frequency test exercises playback and the camera on Gaussian and ORCA fixtures. Set `PLAYWRIGHT_CHROMIUM_EXECUTABLE` to use an existing Chromium executable. diff --git a/frontend/matterviz-viewer/package.json b/frontend/matterviz-viewer/package.json index ca8f298e..58344b53 100644 --- a/frontend/matterviz-viewer/package.json +++ b/frontend/matterviz-viewer/package.json @@ -12,32 +12,29 @@ "dev": "vite --host 127.0.0.1", "test": "node --experimental-strip-types --test tests/*.test.ts", "test:frequency": "node tests/browser/frequency.mjs", - "test:topology-picking": "node tests/browser/topology-picking.mjs", "preview:session": "node scripts/preview-session.mjs", - "test:representations": "node tests/browser/representations.mjs", - "test:scene-export": "node tests/browser/scene-export.mjs", - "test:rep-color": "node tests/browser/rep-color.mjs", - "test:color-scale": "node tests/browser/color-scale.mjs" + "test:scene-export": "node tests/browser/scene-export.mjs" }, "dependencies": { "@lucide/svelte": "1.45.0", - "@threlte/core": "8.5.16", + "@threlte/core": "^8.7.0", + "@threlte/extras": "^9.23.1", "bits-ui": "^2.19.2", "clsx": "^2.1.1", "d3-contour": "^4.0.2", "jspdf": "^4.2.1", - "matterviz": "file:vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.freq1.tgz", - "svelte": "^5.56.4", + "matterviz": "github:janosh/matterviz#main", + "svelte": "^5.57.3", "svg2pdf.js": "^2.7.0", "tailwind-merge": "^3.7.0", "tailwind-variants": "^3.3.1", - "three": "0.185.1" + "three": "^0.187.0" }, "devDependencies": { "@sveltejs/vite-plugin-svelte": "^7.2.0", "@tailwindcss/vite": "^4.3.3", "@types/node": "^24.13.4", - "@types/three": "0.185.1", + "@types/three": "^0.187.0", "playwright": "1.58.2", "svelte-check": "^4.7.2", "tailwindcss": "^4.3.3", diff --git a/frontend/matterviz-viewer/pnpm-lock.yaml b/frontend/matterviz-viewer/pnpm-lock.yaml index b33f0cfb..813b96ec 100644 --- a/frontend/matterviz-viewer/pnpm-lock.yaml +++ b/frontend/matterviz-viewer/pnpm-lock.yaml @@ -10,13 +10,16 @@ importers: dependencies: '@lucide/svelte': specifier: 1.45.0 - version: 1.45.0(svelte@5.56.4) + version: 1.45.0(svelte@5.58.0) '@threlte/core': - specifier: 8.5.16 - version: 8.5.16(svelte@5.56.4)(three@0.185.1) + specifier: ^8.7.0 + version: 8.7.0(svelte@5.58.0)(three@0.187.0) + '@threlte/extras': + specifier: ^9.23.1 + version: 9.23.1(@types/three@0.187.0)(svelte@5.58.0)(three@0.187.0) bits-ui: specifier: ^2.19.2 - version: 2.19.2(@internationalized/date@3.12.4)(@sveltejs/kit@2.69.2(@sveltejs/vite-plugin-svelte@7.2.0(svelte@5.56.4)(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0)))(svelte@5.56.4)(typescript@6.0.3)(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0)))(svelte@5.56.4) + version: 2.19.2(@internationalized/date@3.12.4)(svelte@5.58.0) clsx: specifier: ^2.1.1 version: 2.1.1 @@ -27,11 +30,11 @@ importers: specifier: ^4.2.1 version: 4.2.1 matterviz: - specifier: file:vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.freq1.tgz - version: file:vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.freq1.tgz(@sveltejs/vite-plugin-svelte@7.2.0(svelte@5.56.4)(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0)))(@types/three@0.185.1)(svelte@5.56.4)(typescript@6.0.3)(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0)) + specifier: github:janosh/matterviz#main + version: https://codeload.github.com/janosh/matterviz/tar.gz/218127d1f22d1cffcf07affb95c12b3ce9d90ef3(@types/three@0.187.0)(svelte@5.58.0)(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0)) svelte: - specifier: ^5.56.4 - version: 5.56.4 + specifier: ^5.57.3 + version: 5.58.0 svg2pdf.js: specifier: ^2.7.0 version: 2.7.0(jspdf@4.2.1) @@ -42,12 +45,12 @@ importers: specifier: ^3.3.1 version: 3.3.1(tailwind-merge@3.7.0)(tailwindcss@4.3.3) three: - specifier: 0.185.1 - version: 0.185.1 + specifier: ^0.187.0 + version: 0.187.0 devDependencies: '@sveltejs/vite-plugin-svelte': specifier: ^7.2.0 - version: 7.2.0(svelte@5.56.4)(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0)) + version: 7.2.0(svelte@5.58.0)(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0)) '@tailwindcss/vite': specifier: ^4.3.3 version: 4.3.3(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0)) @@ -55,14 +58,14 @@ importers: specifier: ^24.13.4 version: 24.13.4 '@types/three': - specifier: 0.185.1 - version: 0.185.1 + specifier: ^0.187.0 + version: 0.187.0 playwright: specifier: 1.58.2 version: 1.58.2 svelte-check: specifier: ^4.7.2 - version: 4.7.2(picomatch@4.0.5)(svelte@5.56.4)(typescript@6.0.3) + version: 4.7.2(picomatch@4.0.5)(svelte@5.58.0)(typescript@6.0.3) tailwindcss: specifier: ^4.3.3 version: 4.3.3 @@ -119,6 +122,9 @@ packages: '@jridgewell/sourcemap-codec@1.5.5': resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==} + '@jridgewell/sourcemap-codec@1.6.0': + resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==} + '@jridgewell/trace-mapping@0.3.31': resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} @@ -136,9 +142,6 @@ packages: '@oxc-project/types@0.139.0': resolution: {integrity: sha512-r9gHphtCs+1M7J0pw6Sn/hh/Wpa/iQrOOkrNAlVLF/gHq+/CJmHIWKKUUhdWjcD6CIa8idarspCsASiXCXvFUw==} - '@polka/url@1.0.0-next.29': - resolution: {integrity: sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww==} - '@rolldown/binding-android-arm64@1.1.5': resolution: {integrity: sha512-lZg8fqIv2v7FF237bwMgzGZEJvGL79/s5knJ/i6FmsGF4XXlzccZ4jb+TrFIxtSSxFtIpdsgrPZeMk1I9AFcyQ==} engines: {node: ^20.19.0 || >=22.12.0} @@ -237,33 +240,14 @@ packages: '@rolldown/pluginutils@1.0.1': resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} - '@spglib/moyo-wasm@0.14.0': - resolution: {integrity: sha512-BJ9RP7oKN+Eo4HaeHAhBDRaMmuYh5208EV0O4/RIqpbJjJ0Djmnt+9XaeEVEYegZ5onawYpyS3+ugq4hzDhdgQ==} + '@spglib/moyo-wasm@0.22.0': + resolution: {integrity: sha512-Yyw5FwZ1J+lWNlW1Vgb142ExAItiJYprP7/1Cb10BtB1TZ6dfZsAppJz2tz4ZYa4hwKmsTSCeXU251q+w1gDHA==} - '@standard-schema/spec@1.1.0': - resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} - - '@sveltejs/acorn-typescript@1.0.11': - resolution: {integrity: sha512-LFuZUkjJ9iF7JZye/aG5XM0SFcQ5VyL0oVX4WJ9dc0Va3R3s0OauX1BESVCb+YN/ol8TAfqGDDAQsTG627Y5kw==} + '@sveltejs/acorn-typescript@1.0.13': + resolution: {integrity: sha512-wgKggnhZVL9Bfx1OaKKTrYY9BFRk6C8UAkQNUcIv1+llzYrIqy+RZm5HPKzn0NpEBvTVhTqB4kQyllZywsRBRQ==} peerDependencies: acorn: ^8.9.0 - '@sveltejs/kit@2.69.2': - resolution: {integrity: sha512-CMdPDbYjRwRu4KXTxBVMuOpFPCt1i/v0ANennotec+K9Cmb2e3w2yYzJiC6Vh/WSvm9Khi5sJMZa0rJPqfHlDw==} - engines: {node: '>=18.13'} - hasBin: true - peerDependencies: - '@opentelemetry/api': ^1.0.0 - '@sveltejs/vite-plugin-svelte': ^3.0.0 || ^4.0.0-next.1 || ^5.0.0 || ^6.0.0-next.0 || ^7.0.0 - svelte: ^4.0.0 || ^5.0.0-next.0 - typescript: ^5.3.3 || ^6.0.0 - vite: ^5.0.3 || ^6.0.0 || ^7.0.0-beta.0 || ^8.0.0 - peerDependenciesMeta: - '@opentelemetry/api': - optional: true - typescript: - optional: true - '@sveltejs/load-config@0.2.0': resolution: {integrity: sha512-1LgZ/qUqSoq+QorD83lk2hka79Px0wXNW2q5V1nZlxGhQgw1jrsIbVz5YiCeucVLo4XvFLjXukUaQjIiqowkcg==} engines: {node: '>= 18.0.0'} @@ -377,17 +361,17 @@ packages: peerDependencies: three: '>=0.170.0' - '@threlte/core@8.5.16': - resolution: {integrity: sha512-+aa9Zgz0/Qat82H0hTm1pTEtS2BIP1Nfu7pKaei+3+TvDqER0YnZ4hdgI9fYU9Z5r1lrzY3JxMyrdISp4B0kfw==} + '@threlte/core@8.7.0': + resolution: {integrity: sha512-8WbRlCy33soqiVwIQZZvPAtzWR6Y2i7AwOTpDIcFcsX/Ph0GWIIjsDxg4qcX0gbRp6ym76i1+CBU4dd0gA1g5Q==} peerDependencies: svelte: '>=5' - three: '>=0.160' + three: '>=0.172' - '@threlte/extras@9.21.0': - resolution: {integrity: sha512-ZkBx4IH+7vcxVM09Rex9XJNMKKbQt4JZ5J/3TnBd/Fge8IzSgl0ydgn70riDf/8tDLMDID6VdZPPrlr5vCHHJA==} + '@threlte/extras@9.23.1': + resolution: {integrity: sha512-6G3RXUTiQD3uT5YfHs7vN2r3cjP3y9vtl9m6/wucPrcuyq5QsTIpYUiE8NL+/M+ystAAByu12ntAwy9uJ5MGzg==} peerDependencies: svelte: '>=5' - three: '>=0.160' + three: '>=0.172' '@tweenjs/tween.js@23.1.3': resolution: {integrity: sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==} @@ -395,9 +379,6 @@ packages: '@tybys/wasm-util@0.10.3': resolution: {integrity: sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==} - '@types/cookie@0.6.0': - resolution: {integrity: sha512-4Kh9a6B2bQciAhf7FSuMRRkUWecJgJu9nPnx3yzpsfXX/c50REIqpHY4C82bXP90qrLtXtkDxTZosYO3UpOwlA==} - '@types/estree@1.0.9': resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} @@ -413,8 +394,8 @@ packages: '@types/stats.js@0.17.4': resolution: {integrity: sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA==} - '@types/three@0.185.1': - resolution: {integrity: sha512-db1xTb+EgYF2didW+eudSvVPtn75zo+fGsY8ShQrJY/B5ZBmC2Fiaykv3aImHAlCNEGuMPkPGXBJGLwzu5mC7A==} + '@types/three@0.187.0': + resolution: {integrity: sha512-v+vKNarUtk4n2QRZ4+CN5ygMM0ARUjXjIQl0R/unMUfmStFeVqGbgqarbrpoGTXRZoulSH16ePrVJVxPJEbMUA==} '@types/trusted-types@2.0.7': resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==} @@ -422,13 +403,13 @@ packages: '@types/webxr@0.5.24': resolution: {integrity: sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==} - acorn@8.17.0: - resolution: {integrity: sha512-xRQbDb9BnwDafYNn6Vwl839DYVjqXYb1XVGtWAZ1kcDc6iwAL4hg3B1dZlRiuENFeO2H53gFG3in621AdERVAg==} + acorn@8.19.0: + resolution: {integrity: sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==} engines: {node: '>=0.4.0'} hasBin: true - argparse@2.0.1: - resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==} + argparse@3.0.4: + resolution: {integrity: sha512-fwWK3Zq22l4XJJjx5mcBHGikIk+hJqO+32dPm0Jur7+rtG5x1scOjSfdT9ZKeWHPpsya/l0HHK4tDImBkTrtvA==} aria-query@5.3.1: resolution: {integrity: sha512-Z/ZeOgVl7bcSYZ/u/rh0fOpvEpq//LZmdbkXyc7syVzjPAhfOa9ebsdTSjEBDU4vs5nC98Kfduj1uFo0qyET3g==} @@ -470,10 +451,6 @@ packages: resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==} engines: {node: '>=6'} - cookie@0.6.0: - resolution: {integrity: sha512-U71cyTamuh1CRNCfpGY6to28lxvNwPG4Guz/EVjgf3Jmzv0vlDp1atT9eS5dDjMYHucpHbWns6Lwf3BKz6svdw==} - engines: {node: '>= 0.6'} - core-js@3.49.0: resolution: {integrity: sha512-es1U2+YTtzpwkxVLwAFdSpaIMyQaq0PBgm3YD1W3Qpsn1NAmO3KSgZfu+oGSWVu6NvLHoHCV/aYcsE5wiB7ALg==} @@ -492,20 +469,32 @@ packages: resolution: {integrity: sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==} engines: {node: '>=12'} + d3-array@3.2.5: + resolution: {integrity: sha512-Th8qGXoBalmWsstpkuhmBuTsBQIFqYOJtjlBvNVvBfJ8E3uYusBUwUR8HU20U0qKKQkgCvKyR1YjiozWadk5QA==} + engines: {node: '>=12'} + d3-color@3.1.0: resolution: {integrity: sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==} engines: {node: '>=12'} + d3-color@3.1.1: + resolution: {integrity: sha512-lfab8x0Bj0UO7SNsY8dZSbNIA6ipbkE3X0NG9nqjCu6CfCHZseuDnOSJY7hidKrjpP++i1M2qT+FlAdPKYRilA==} + engines: {node: '>=12'} + d3-contour@4.0.2: resolution: {integrity: sha512-4EzFTRIikzs47RGmdxbeUvLWtGedDUNkTcmzoeyg4sP/dvCexO47AaQL7VKy/gul85TOxw+IBgA8US2xwbToNA==} engines: {node: '>=12'} + d3-contour@4.0.3: + resolution: {integrity: sha512-5DYURc8KwXPOhSUBblU0P9rVcArsSPxPOxsfO0Eud0s28oU0sB2e80aRHRL9AZW3usT8ikFKyIHpHHLNWLdRVA==} + engines: {node: '>=12'} + d3-format@3.1.2: resolution: {integrity: sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg==} engines: {node: '>=12'} - d3-hierarchy@3.1.2: - resolution: {integrity: sha512-FX/9frcub54beBdugHjDCdikxThEqjnR93Qt7PvQTOHxyiNCAlvMrHhclk3cD5VeAaq9fxmfRp+CnWw9rEMBuA==} + d3-hierarchy@3.1.3: + resolution: {integrity: sha512-GRajN5ZcnEwYFWqqdzhG1qJ3+fDg6WWzk47TJg7ePY7yvYAgRfD2r1mUx+wviBOWuCwamCUzjwMSdato43jbGA==} engines: {node: '>=12'} d3-interpolate-path@2.3.0: @@ -518,32 +507,40 @@ packages: d3-path@1.0.9: resolution: {integrity: sha512-VLaYcn81dtHVTjEHd8B+pbe9yHWpXKZUC87PzoFmsFrJqgFwDe/qxfp5MlfsfM1V5E/iVt0MmEbWQ7FVIXh/bg==} - d3-path@3.1.0: - resolution: {integrity: sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==} + d3-path@3.1.1: + resolution: {integrity: sha512-jsbgV8zIT38ReB9O7X7gcLndTQRONSqNNd+oGIaTBdUug4r5jFmp0N6RY9R5GWbdUDucn0qoTGyfjapT4tDhcg==} engines: {node: '>=12'} d3-sankey@0.12.3: resolution: {integrity: sha512-nQhsBRmM19Ax5xEIPLMY9ZmJ/cDvd1BG3UVvt5h3WRxKg5zGRbvnteTyWAbzeSvlh3tW7ZEmq4VwR5mB3tutmQ==} - d3-scale-chromatic@3.1.0: - resolution: {integrity: sha512-A3s5PWiZ9YCXFye1o246KoscMWqf8BsD9eRiJ3He7C9OBaxKhAd5TFCdEx/7VbKtxxTsu//1mMJFrEt572cEyQ==} + d3-scale-chromatic@3.1.1: + resolution: {integrity: sha512-lA5gfN2yMvmChubmptnDiBfeGpHD7Yb1EbvCz0TZE0WHXhyR6W2allPuhKtzV5ILQRqeOdefF0qYtERReLUBDg==} engines: {node: '>=12'} d3-scale@4.0.2: resolution: {integrity: sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==} engines: {node: '>=12'} + d3-scale@4.0.3: + resolution: {integrity: sha512-66cWobCNzcMvlfoaDHCxuIv9TBUWG1BLOWdv9kHHFuCr1JdqAWPvTmsaEYDD5NRMyWZ5+7u0GqiCDfMXMqh3hg==} + engines: {node: '>=12'} + d3-shape@1.3.7: resolution: {integrity: sha512-EUkvKjqPFUAZyOlhY5gzCxCeI0Aep04LwIRpsZ/mLFelJiUfnK56jo5JMDSE7yyP2kLSb6LtF+S5chMk7uqPqw==} - d3-shape@3.2.0: - resolution: {integrity: sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==} + d3-shape@3.2.1: + resolution: {integrity: sha512-dm2o+lbKdzg9tY7GEag/dB9hcbodLfwkE/DkvqbELJXaMz0yKzWWhZqhbI7CKubukA7HnRyz0avdtvi7EPxPvw==} engines: {node: '>=12'} d3-time-format@4.1.0: resolution: {integrity: sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==} engines: {node: '>=12'} + d3-time-format@4.1.1: + resolution: {integrity: sha512-22XaqjyCjpqgda20erhsOjGmC3vvYwTNYniKAd45W5UWLDF43moeOuV9qYpRqobIlsnK0UhnKZjUUJm3VgORUA==} + engines: {node: '>=12'} + d3-time@3.1.0: resolution: {integrity: sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==} engines: {node: '>=12'} @@ -560,12 +557,15 @@ packages: resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} engines: {node: '>=8'} - devalue@5.8.1: - resolution: {integrity: sha512-4CXDYRBGqN+57wVJkuXBYmpAVUSg3L6JAQa/DFqm238G73E1wuyc/JhGQJzN7vUf/CMphYau2zXbfWzDR5aTEw==} + devalue@5.9.4: + resolution: {integrity: sha512-sPAT4pztbu6586/hrhOnMKS17IJrvg12mXiSPSS3W5qDeN2RGgvZ0diZCm31dBbnevfVmujNO3IM2wrS4Y2Rhg==} diet-sprite@0.0.1: resolution: {integrity: sha512-zSHI2WDAn1wJqJYxcmjWfJv3Iw8oL9reQIbEyx2x2/EZ4/qmUTIo8/5qOCurnAcq61EwtJJaZ0XTy2NRYqpB5A==} + dompurify@3.4.18: + resolution: {integrity: sha512-ofe3wI/uNm68HInABYFJYqQxRw1EaKAjNdrFVKqjUY+UZurvNd2L/HuQe097s/4RivWiZyP6tT7aoT8atjfhwg==} + dompurify@3.4.7: resolution: {integrity: sha512-2jBxDJY4RR06tQNy4w5FlFH7kfxsQZlufd0sbv+chfHCxeJwrFw2baUDsSwvBISD4K4RDbd0PTfy3uNXsR6siA==} @@ -579,8 +579,8 @@ packages: esm-env@1.2.2: resolution: {integrity: sha512-Epxrv+Nr/CaL4ZcFGPJIYLWFom+YeV1DqMLHJoEd9SYRxNbaFruBwfEX/kkHUJf55j2+TUbmDcmuilbP1TmXHA==} - esrap@2.2.13: - resolution: {integrity: sha512-m8jH5hZgJE2RRUK/jjkGPcJEDAV+dYnZYFkosQaPTcE+Yw4xynXHOo6FUdwaWBtdR3b1MMa7wEDTSHeR2VWsGA==} + esrap@2.4.2: + resolution: {integrity: sha512-WpVZsWnSheHBy+fGrO/0duwnbe6ODZH1QyBbjupreSCJGojaBWRncrq+HVeIJ8eHQjEwSJg9hC4yPJyNVOrpqg==} peerDependencies: '@typescript-eslint/types': ^8.2.0 peerDependenciesMeta: @@ -645,17 +645,13 @@ packages: resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==} hasBin: true - js-yaml@5.2.1: - resolution: {integrity: sha512-zfLtNfQqxVqq3uaTqSkh4x4hZw3KHobGUA0fJUj4wawW8bsQLTVqpHdXSIzidh7o+4lEW36tANuAGdaFx6Zgnw==} + js-yaml@5.5.0: + resolution: {integrity: sha512-paNr4LFIFPjeeSmwNYdrb8FafLLG/Cr2Af3GjbsHJ5CxIjH4r0c2emlmRdAtpPAieP1gRVzk6buBbVP5gBMGAg==} hasBin: true jspdf@4.2.1: resolution: {integrity: sha512-YyAXyvnmjTbR4bHQRLzex3CuINCDlQnBqoSYyjJwTP2x9jDLuKDzy7aKUl0hgx3uhcl7xzg32agn5vlie6HIlQ==} - kleur@4.1.5: - resolution: {integrity: sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==} - engines: {node: '>=6'} - lightningcss-android-arm64@1.32.0: resolution: {integrity: sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==} engines: {node: '>= 12.0.0'} @@ -746,12 +742,17 @@ packages: magic-string@0.30.21: resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} - matterviz@file:vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.freq1.tgz: - resolution: {integrity: sha512-T3JKF941cgq8i1Ios5TljjSbsvpO/SdnwEBJ4kQbH1HJZv/dX3C9xtsl0sGs+KHka00tAsZl72MN6VyxCqhPGQ==, tarball: file:vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.freq1.tgz} - version: 0.4.2-multiwfn.d8719d12.r25.freq1 + marked@18.2.1: + resolution: {integrity: sha512-ii4bxCTCqqwpT86XZWgJNs+ZnAIZksmLGYMViWA7PDIXYIeNo1x6cDdX3JOip9NM/cI6p8z57FxliACboTruMA==} + engines: {node: '>= 20'} + hasBin: true + + matterviz@https://codeload.github.com/janosh/matterviz/tar.gz/218127d1f22d1cffcf07affb95c12b3ce9d90ef3: + resolution: {gitHosted: true, tarball: https://codeload.github.com/janosh/matterviz/tar.gz/218127d1f22d1cffcf07affb95c12b3ce9d90ef3} + version: 0.9.0 engines: {node: '>=24'} peerDependencies: - svelte: ^5.0.0 + svelte: ^5.48.0 meshoptimizer@1.1.1: resolution: {integrity: sha512-oRFNWJRDA/WTrVj7NWvqa5HqE1t9MYDj2VaWirQCzCCrAd2GHrqR/sQezCxiWATPNlKTcRaPRHPJwIRoPBAp5g==} @@ -760,10 +761,6 @@ packages: resolution: {integrity: sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==} engines: {node: '>=4'} - mrmime@2.0.1: - resolution: {integrity: sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ==} - engines: {node: '>=10'} - nanoid@3.3.15: resolution: {integrity: sha512-y7Wygv/7mEOvxTuEQDB8StXdMRBWf1kR/tlhAzBRUFkB2jfcLOAxO/SHmOO2zgz1pVgK29/kyupn059/bCHdjA==} engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} @@ -836,13 +833,6 @@ packages: resolution: {integrity: sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A==} engines: {node: '>=6'} - set-cookie-parser@3.1.2: - resolution: {integrity: sha512-5/r/lTwbJ3zQ+qwdUFZYeRNqda7P5HD8zQKqlSjdGt1/S0cjLAphHusj4Y58ahDtWn/g32xrIS58/ikOvwl0Lw==} - - sirv@3.0.2: - resolution: {integrity: sha512-2wcC/oGxHis/BoHkkPwldgiPSYcpZK3JU28WoMVv55yHJgcZ8rlXvuG9iZggz+sU1d4bRgIGASwyWqjxu3FM0g==} - engines: {node: '>=18'} - source-map-js@1.2.1: resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} engines: {node: '>=0.10.0'} @@ -866,26 +856,33 @@ packages: svelte: ^4.0.0 || ^5.0.0-next.0 typescript: '>=5.0.0' - svelte-multiselect@11.8.0: - resolution: {integrity: sha512-B+y6UPZCB9/EWk9a0kxBkN4Z05bMj8g10N2RK6CNLrkRDD2iS1hLs1jJTWuQUDSbUofNChLk6kqx9nSrs8xzwQ==} + svelte-toolbelt@0.10.6: + resolution: {integrity: sha512-YWuX+RE+CnWYx09yseAe4ZVMM7e7GRFZM6OYWpBKOb++s+SQ8RBIMMe+Bs/CznBMc0QPLjr+vDBxTAkozXsFXQ==} + engines: {node: '>=18', pnpm: '>=8.7.0'} + peerDependencies: + svelte: ^5.30.2 + + svelte-widgets@https://codeload.github.com/janosh/svelte-widgets/tar.gz/55345ea3d59913ff1abb66f87ef778eea517e304: + resolution: {gitHosted: true, tarball: https://codeload.github.com/janosh/svelte-widgets/tar.gz/55345ea3d59913ff1abb66f87ef778eea517e304} + version: 1.11.0 peerDependencies: '@wooorm/starry-night': ^3.0.0 + mermaid: ^12.0.0 svelte: ^5.48.0 + temml: ^0.14.0 vite: ^8.0.0 peerDependenciesMeta: '@wooorm/starry-night': optional: true + mermaid: + optional: true + temml: + optional: true vite: optional: true - svelte-toolbelt@0.10.6: - resolution: {integrity: sha512-YWuX+RE+CnWYx09yseAe4ZVMM7e7GRFZM6OYWpBKOb++s+SQ8RBIMMe+Bs/CznBMc0QPLjr+vDBxTAkozXsFXQ==} - engines: {node: '>=18', pnpm: '>=8.7.0'} - peerDependencies: - svelte: ^5.30.2 - - svelte@5.56.4: - resolution: {integrity: sha512-/d0QHehmRuJW8gVz395MTkPcPozxzdjBMBE8oEYGz8O3b9KTMzzQ9ZHJQLuFKOHOPQbU6kx/X4iid/EBBzH7iw==} + svelte@5.58.0: + resolution: {integrity: sha512-rOMKTD9WP2C6ahWDmntey4p+JqUxtup1w9G3KdVuTbNGHi5u97iMw0CIc8a+F5rZtiH7x98kVniDlBRRR5e98w==} engines: {node: '>=18'} svg-pathdata@6.0.3: @@ -943,22 +940,13 @@ packages: peerDependencies: three: '>=0.170' - three-viewport-gizmo@2.2.0: - resolution: {integrity: sha512-Jo9Liur1rUmdKk75FZumLU/+hbF+RtJHi1qsKZpntjKlCYScK6tjbYoqvJ9M+IJphrlQJF5oReFW7Sambh0N4Q==} - peerDependencies: - three: '>=0.162.0 <1.0.0' - - three@0.185.1: - resolution: {integrity: sha512-5aojFCXKwnjBRZvUnt3WFfEcvUJgkN5LlijRFN95hMy8WVkG4I0QNcJE+OuWvuJ0bOdStrbfXn0pkd6/QyiAlg==} + three@0.187.0: + resolution: {integrity: sha512-Qiu7R+Cmh8CstZsY1uJOSWnVlfo7ZtNLV7mF8Jltk3LB3AtDu9cRZlcnRKkAk8Y4z6KKw35z7Y7Urd7jWY8etA==} tinyglobby@0.2.17: resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} engines: {node: '>=12.0.0'} - totalist@3.0.1: - resolution: {integrity: sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ==} - engines: {node: '>=6'} - troika-three-text@0.52.4: resolution: {integrity: sha512-V50EwcYGruV5rUZ9F4aNsrytGdKcXKALjEtQXIOBfhVoZU9VAqZNIoGQ3TMiooVqFAbR1w15T+f+8gkzoFzawg==} peerDependencies: @@ -1100,14 +1088,16 @@ snapshots: '@jridgewell/sourcemap-codec@1.5.5': {} + '@jridgewell/sourcemap-codec@1.6.0': {} + '@jridgewell/trace-mapping@0.3.31': dependencies: '@jridgewell/resolve-uri': 3.1.2 '@jridgewell/sourcemap-codec': 1.5.5 - '@lucide/svelte@1.45.0(svelte@5.56.4)': + '@lucide/svelte@1.45.0(svelte@5.58.0)': dependencies: - svelte: 5.56.4 + svelte: 5.58.0 '@napi-rs/wasm-runtime@1.1.6(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1)': dependencies: @@ -1118,8 +1108,6 @@ snapshots: '@oxc-project/types@0.139.0': {} - '@polka/url@1.0.0-next.29': {} - '@rolldown/binding-android-arm64@1.1.5': optional: true @@ -1171,42 +1159,20 @@ snapshots: '@rolldown/pluginutils@1.0.1': {} - '@spglib/moyo-wasm@0.14.0': {} - - '@standard-schema/spec@1.1.0': {} - - '@sveltejs/acorn-typescript@1.0.11(acorn@8.17.0)': - dependencies: - acorn: 8.17.0 + '@spglib/moyo-wasm@0.22.0': {} - '@sveltejs/kit@2.69.2(@sveltejs/vite-plugin-svelte@7.2.0(svelte@5.56.4)(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0)))(svelte@5.56.4)(typescript@6.0.3)(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0))': + '@sveltejs/acorn-typescript@1.0.13(acorn@8.19.0)': dependencies: - '@standard-schema/spec': 1.1.0 - '@sveltejs/acorn-typescript': 1.0.11(acorn@8.17.0) - '@sveltejs/vite-plugin-svelte': 7.2.0(svelte@5.56.4)(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0)) - '@types/cookie': 0.6.0 - acorn: 8.17.0 - cookie: 0.6.0 - devalue: 5.8.1 - esm-env: 1.2.2 - kleur: 4.1.5 - magic-string: 0.30.21 - mrmime: 2.0.1 - set-cookie-parser: 3.1.2 - sirv: 3.0.2 - svelte: 5.56.4 - vite: 8.1.4(@types/node@24.13.4)(jiti@2.7.0) - optionalDependencies: - typescript: 6.0.3 + acorn: 8.19.0 '@sveltejs/load-config@0.2.0': {} - '@sveltejs/vite-plugin-svelte@7.2.0(svelte@5.56.4)(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0))': + '@sveltejs/vite-plugin-svelte@7.2.0(svelte@5.58.0)(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0))': dependencies: deepmerge: 4.3.1 magic-string: 0.30.21 obug: 2.1.3 - svelte: 5.56.4 + svelte: 5.58.0 vite: 8.1.4(@types/node@24.13.4)(jiti@2.7.0) vitefu: 1.1.3(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0)) @@ -1282,32 +1248,31 @@ snapshots: tailwindcss: 4.3.3 vite: 8.1.4(@types/node@24.13.4)(jiti@2.7.0) - '@threejs-kit/instanced-sprite-mesh@2.5.1(@types/three@0.185.1)(three@0.185.1)': + '@threejs-kit/instanced-sprite-mesh@2.5.1(@types/three@0.187.0)(three@0.187.0)': dependencies: diet-sprite: 0.0.1 earcut: 2.2.4 - maath: 0.10.8(@types/three@0.185.1)(three@0.185.1) - three: 0.185.1 - three-instanced-uniforms-mesh: 0.52.4(three@0.185.1) - troika-three-utils: 0.52.4(three@0.185.1) + maath: 0.10.8(@types/three@0.187.0)(three@0.187.0) + three: 0.187.0 + three-instanced-uniforms-mesh: 0.52.4(three@0.187.0) + troika-three-utils: 0.52.4(three@0.187.0) transitivePeerDependencies: - '@types/three' - '@threlte/core@8.5.16(svelte@5.56.4)(three@0.185.1)': + '@threlte/core@8.7.0(svelte@5.58.0)(three@0.187.0)': dependencies: - svelte: 5.56.4 - three: 0.185.1 + svelte: 5.58.0 + three: 0.187.0 - '@threlte/extras@9.21.0(@types/three@0.185.1)(svelte@5.56.4)(three@0.185.1)': + '@threlte/extras@9.23.1(@types/three@0.187.0)(svelte@5.58.0)(three@0.187.0)': dependencies: - '@threejs-kit/instanced-sprite-mesh': 2.5.1(@types/three@0.185.1)(three@0.185.1) - camera-controls: 3.1.2(three@0.185.1) - svelte: 5.56.4 - three: 0.185.1 - three-mesh-bvh: 0.9.11(three@0.185.1) - three-perf: 1.0.11(three@0.185.1) - three-viewport-gizmo: 2.2.0(three@0.185.1) - troika-three-text: 0.52.4(three@0.185.1) + '@threejs-kit/instanced-sprite-mesh': 2.5.1(@types/three@0.187.0)(three@0.187.0) + camera-controls: 3.1.2(three@0.187.0) + svelte: 5.58.0 + three: 0.187.0 + three-mesh-bvh: 0.9.11(three@0.187.0) + three-perf: 1.0.11(three@0.187.0) + troika-three-text: 0.52.4(three@0.187.0) transitivePeerDependencies: - '@types/three' @@ -1318,8 +1283,6 @@ snapshots: tslib: 2.8.1 optional: true - '@types/cookie@0.6.0': {} - '@types/estree@1.0.9': {} '@types/node@24.13.4': @@ -1333,7 +1296,7 @@ snapshots: '@types/stats.js@0.17.4': {} - '@types/three@0.185.1': + '@types/three@0.187.0': dependencies: '@dimforge/rapier3d-compat': 0.12.0 '@tweenjs/tween.js': 23.1.3 @@ -1342,13 +1305,14 @@ snapshots: fflate: 0.8.3 meshoptimizer: 1.1.1 - '@types/trusted-types@2.0.7': {} + '@types/trusted-types@2.0.7': + optional: true '@types/webxr@0.5.24': {} - acorn@8.17.0: {} + acorn@8.19.0: {} - argparse@2.0.1: {} + argparse@3.0.4: {} aria-query@5.3.1: {} @@ -1361,22 +1325,22 @@ snapshots: dependencies: require-from-string: 2.0.2 - bits-ui@2.19.2(@internationalized/date@3.12.4)(@sveltejs/kit@2.69.2(@sveltejs/vite-plugin-svelte@7.2.0(svelte@5.56.4)(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0)))(svelte@5.56.4)(typescript@6.0.3)(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0)))(svelte@5.56.4): + bits-ui@2.19.2(@internationalized/date@3.12.4)(svelte@5.58.0): dependencies: '@floating-ui/core': 1.8.0 '@floating-ui/dom': 1.8.0 '@internationalized/date': 3.12.4 esm-env: 1.2.2 - runed: 0.35.1(@sveltejs/kit@2.69.2(@sveltejs/vite-plugin-svelte@7.2.0(svelte@5.56.4)(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0)))(svelte@5.56.4)(typescript@6.0.3)(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0)))(svelte@5.56.4) - svelte: 5.56.4 - svelte-toolbelt: 0.10.6(@sveltejs/kit@2.69.2(@sveltejs/vite-plugin-svelte@7.2.0(svelte@5.56.4)(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0)))(svelte@5.56.4)(typescript@6.0.3)(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0)))(svelte@5.56.4) + runed: 0.35.1(svelte@5.58.0) + svelte: 5.58.0 + svelte-toolbelt: 0.10.6(svelte@5.58.0) tabbable: 6.5.0 transitivePeerDependencies: - '@sveltejs/kit' - camera-controls@3.1.2(three@0.185.1): + camera-controls@3.1.2(three@0.187.0): dependencies: - three: 0.185.1 + three: 0.187.0 canvg@3.0.11: dependencies: @@ -1396,8 +1360,6 @@ snapshots: clsx@2.1.1: {} - cookie@0.6.0: {} - core-js@3.49.0: optional: true @@ -1416,15 +1378,25 @@ snapshots: dependencies: internmap: 2.0.3 + d3-array@3.2.5: + dependencies: + internmap: 2.0.3 + d3-color@3.1.0: {} + d3-color@3.1.1: {} + d3-contour@4.0.2: dependencies: d3-array: 3.2.4 + d3-contour@4.0.3: + dependencies: + d3-array: 3.2.4 + d3-format@3.1.2: {} - d3-hierarchy@3.1.2: {} + d3-hierarchy@3.1.3: {} d3-interpolate-path@2.3.0: {} @@ -1434,17 +1406,18 @@ snapshots: d3-path@1.0.9: {} - d3-path@3.1.0: {} + d3-path@3.1.1: {} d3-sankey@0.12.3: dependencies: d3-array: 2.12.1 d3-shape: 1.3.7 - d3-scale-chromatic@3.1.0: + d3-scale-chromatic@3.1.1: dependencies: d3-color: 3.1.0 d3-interpolate: 3.0.1 + d3-scale: 4.0.2 d3-scale@4.0.2: dependencies: @@ -1454,18 +1427,30 @@ snapshots: d3-time: 3.1.0 d3-time-format: 4.1.0 + d3-scale@4.0.3: + dependencies: + d3-array: 3.2.4 + d3-format: 3.1.2 + d3-interpolate: 3.0.1 + d3-time: 3.1.0 + d3-time-format: 4.1.0 + d3-shape@1.3.7: dependencies: d3-path: 1.0.9 - d3-shape@3.2.0: + d3-shape@3.2.1: dependencies: - d3-path: 3.1.0 + d3-path: 3.1.1 d3-time-format@4.1.0: dependencies: d3-time: 3.1.0 + d3-time-format@4.1.1: + dependencies: + d3-time: 3.1.0 + d3-time@3.1.0: dependencies: d3-array: 3.2.4 @@ -1476,13 +1461,18 @@ snapshots: detect-libc@2.1.2: {} - devalue@5.8.1: {} + devalue@5.9.4: {} diet-sprite@0.0.1: {} + dompurify@3.4.18: + optionalDependencies: + '@types/trusted-types': 2.0.7 + dompurify@3.4.7: optionalDependencies: '@types/trusted-types': 2.0.7 + optional: true earcut@2.2.4: {} @@ -1493,7 +1483,7 @@ snapshots: esm-env@1.2.2: {} - esrap@2.2.13: + esrap@2.4.2: dependencies: '@jridgewell/sourcemap-codec': 1.5.5 @@ -1541,9 +1531,9 @@ snapshots: jiti@2.7.0: {} - js-yaml@5.2.1: + js-yaml@5.5.0: dependencies: - argparse: 2.0.1 + argparse: 3.0.4 jspdf@4.2.1: dependencies: @@ -1556,8 +1546,6 @@ snapshots: dompurify: 3.4.7 html2canvas: 1.4.1 - kleur@4.1.5: {} - lightningcss-android-arm64@1.32.0: optional: true @@ -1611,52 +1599,50 @@ snapshots: lz-string@1.5.0: {} - maath@0.10.8(@types/three@0.185.1)(three@0.185.1): + maath@0.10.8(@types/three@0.187.0)(three@0.187.0): dependencies: - '@types/three': 0.185.1 - three: 0.185.1 + '@types/three': 0.187.0 + three: 0.187.0 magic-string@0.30.21: dependencies: '@jridgewell/sourcemap-codec': 1.5.5 - matterviz@file:vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.freq1.tgz(@sveltejs/vite-plugin-svelte@7.2.0(svelte@5.56.4)(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0)))(@types/three@0.185.1)(svelte@5.56.4)(typescript@6.0.3)(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0)): + marked@18.2.1: {} + + matterviz@https://codeload.github.com/janosh/matterviz/tar.gz/218127d1f22d1cffcf07affb95c12b3ce9d90ef3(@types/three@0.187.0)(svelte@5.58.0)(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0)): dependencies: - '@spglib/moyo-wasm': 0.14.0 - '@sveltejs/kit': 2.69.2(@sveltejs/vite-plugin-svelte@7.2.0(svelte@5.56.4)(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0)))(svelte@5.56.4)(typescript@6.0.3)(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0)) - '@threlte/core': 8.5.16(svelte@5.56.4)(three@0.185.1) - '@threlte/extras': 9.21.0(@types/three@0.185.1)(svelte@5.56.4)(three@0.185.1) - d3-array: 3.2.4 - d3-color: 3.1.0 - d3-format: 3.1.2 - d3-hierarchy: 3.1.2 + '@spglib/moyo-wasm': 0.22.0 + '@threlte/core': 8.7.0(svelte@5.58.0)(three@0.187.0) + '@threlte/extras': 9.23.1(@types/three@0.187.0)(svelte@5.58.0)(three@0.187.0) + d3-array: 3.2.5 + d3-color: 3.1.1 + d3-contour: 4.0.3 + d3-hierarchy: 3.1.3 d3-interpolate-path: 2.3.0 d3-sankey: 0.12.3 - d3-scale: 4.0.2 - d3-scale-chromatic: 3.1.0 - d3-shape: 3.2.0 - d3-time-format: 4.1.0 - dompurify: 3.4.7 + d3-scale: 4.0.3 + d3-scale-chromatic: 3.1.1 + d3-shape: 3.2.1 + d3-time-format: 4.1.1 + dompurify: 3.4.18 fflate: 0.8.3 h5wasm: 0.10.3 - js-yaml: 5.2.1 - svelte: 5.56.4 - svelte-multiselect: 11.8.0(svelte@5.56.4)(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0)) - three: 0.185.1 + js-yaml: 5.5.0 + svelte: 5.58.0 + svelte-widgets: https://codeload.github.com/janosh/svelte-widgets/tar.gz/55345ea3d59913ff1abb66f87ef778eea517e304(svelte@5.58.0)(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0)) + three: 0.187.0 transitivePeerDependencies: - - '@opentelemetry/api' - - '@sveltejs/vite-plugin-svelte' - '@types/three' - '@wooorm/starry-night' - - typescript + - mermaid + - temml - vite meshoptimizer@1.1.1: {} mri@1.2.0: {} - mrmime@2.0.1: {} - nanoid@3.3.15: {} obug@2.1.3: {} @@ -1720,27 +1706,17 @@ snapshots: '@rolldown/binding-win32-arm64-msvc': 1.1.5 '@rolldown/binding-win32-x64-msvc': 1.1.5 - runed@0.35.1(@sveltejs/kit@2.69.2(@sveltejs/vite-plugin-svelte@7.2.0(svelte@5.56.4)(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0)))(svelte@5.56.4)(typescript@6.0.3)(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0)))(svelte@5.56.4): + runed@0.35.1(svelte@5.58.0): dependencies: dequal: 2.0.3 esm-env: 1.2.2 lz-string: 1.5.0 - svelte: 5.56.4 - optionalDependencies: - '@sveltejs/kit': 2.69.2(@sveltejs/vite-plugin-svelte@7.2.0(svelte@5.56.4)(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0)))(svelte@5.56.4)(typescript@6.0.3)(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0)) + svelte: 5.58.0 sade@1.8.1: dependencies: mri: 1.2.0 - set-cookie-parser@3.1.2: {} - - sirv@3.0.2: - dependencies: - '@polka/url': 1.0.0-next.29 - mrmime: 2.0.1 - totalist: 3.0.1 - source-map-js@1.2.1: {} specificity@0.4.1: {} @@ -1752,7 +1728,7 @@ snapshots: dependencies: inline-style-parser: 0.2.7 - svelte-check@4.7.2(picomatch@4.0.5)(svelte@5.56.4)(typescript@6.0.3): + svelte-check@4.7.2(picomatch@4.0.5)(svelte@5.58.0)(typescript@6.0.3): dependencies: '@jridgewell/trace-mapping': 0.3.31 '@sveltejs/load-config': 0.2.0 @@ -1760,40 +1736,41 @@ snapshots: fdir: 6.5.0(picomatch@4.0.5) picocolors: 1.1.1 sade: 1.8.1 - svelte: 5.56.4 + svelte: 5.58.0 typescript: 6.0.3 transitivePeerDependencies: - picomatch - svelte-multiselect@11.8.0(svelte@5.56.4)(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0)): - dependencies: - svelte: 5.56.4 - optionalDependencies: - vite: 8.1.4(@types/node@24.13.4)(jiti@2.7.0) - - svelte-toolbelt@0.10.6(@sveltejs/kit@2.69.2(@sveltejs/vite-plugin-svelte@7.2.0(svelte@5.56.4)(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0)))(svelte@5.56.4)(typescript@6.0.3)(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0)))(svelte@5.56.4): + svelte-toolbelt@0.10.6(svelte@5.58.0): dependencies: clsx: 2.1.1 - runed: 0.35.1(@sveltejs/kit@2.69.2(@sveltejs/vite-plugin-svelte@7.2.0(svelte@5.56.4)(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0)))(svelte@5.56.4)(typescript@6.0.3)(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0)))(svelte@5.56.4) + runed: 0.35.1(svelte@5.58.0) style-to-object: 1.0.14 - svelte: 5.56.4 + svelte: 5.58.0 transitivePeerDependencies: - '@sveltejs/kit' - svelte@5.56.4: + svelte-widgets@https://codeload.github.com/janosh/svelte-widgets/tar.gz/55345ea3d59913ff1abb66f87ef778eea517e304(svelte@5.58.0)(vite@8.1.4(@types/node@24.13.4)(jiti@2.7.0)): + dependencies: + js-yaml: 5.5.0 + marked: 18.2.1 + svelte: 5.58.0 + optionalDependencies: + vite: 8.1.4(@types/node@24.13.4)(jiti@2.7.0) + + svelte@5.58.0: dependencies: '@jridgewell/remapping': 2.3.5 - '@jridgewell/sourcemap-codec': 1.5.5 - '@sveltejs/acorn-typescript': 1.0.11(acorn@8.17.0) + '@jridgewell/sourcemap-codec': 1.6.0 + '@sveltejs/acorn-typescript': 1.0.13(acorn@8.19.0) '@types/estree': 1.0.9 - '@types/trusted-types': 2.0.7 - acorn: 8.17.0 + acorn: 8.19.0 aria-query: 5.3.1 axobject-query: 4.1.0 clsx: 2.1.1 - devalue: 5.8.1 + devalue: 5.9.4 esm-env: 1.2.2 - esrap: 2.2.13 + esrap: 2.4.2 is-reference: 3.0.3 locate-character: 3.0.0 magic-string: 0.30.21 @@ -1832,45 +1809,39 @@ snapshots: utrie: 1.0.2 optional: true - three-instanced-uniforms-mesh@0.52.4(three@0.185.1): + three-instanced-uniforms-mesh@0.52.4(three@0.187.0): dependencies: - three: 0.185.1 - troika-three-utils: 0.52.4(three@0.185.1) + three: 0.187.0 + troika-three-utils: 0.52.4(three@0.187.0) - three-mesh-bvh@0.9.11(three@0.185.1): + three-mesh-bvh@0.9.11(three@0.187.0): dependencies: - three: 0.185.1 + three: 0.187.0 - three-perf@1.0.11(three@0.185.1): + three-perf@1.0.11(three@0.187.0): dependencies: - three: 0.185.1 - troika-three-text: 0.52.4(three@0.185.1) + three: 0.187.0 + troika-three-text: 0.52.4(three@0.187.0) tweakpane: 3.1.10 - three-viewport-gizmo@2.2.0(three@0.185.1): - dependencies: - three: 0.185.1 - - three@0.185.1: {} + three@0.187.0: {} tinyglobby@0.2.17: dependencies: fdir: 6.5.0(picomatch@4.0.5) picomatch: 4.0.5 - totalist@3.0.1: {} - - troika-three-text@0.52.4(three@0.185.1): + troika-three-text@0.52.4(three@0.187.0): dependencies: bidi-js: 1.0.3 - three: 0.185.1 - troika-three-utils: 0.52.4(three@0.185.1) + three: 0.187.0 + troika-three-utils: 0.52.4(three@0.187.0) troika-worker-utils: 0.52.0 webgl-sdf-generator: 1.1.1 - troika-three-utils@0.52.4(three@0.185.1): + troika-three-utils@0.52.4(three@0.187.0): dependencies: - three: 0.185.1 + three: 0.187.0 troika-worker-utils@0.52.0: {} diff --git a/frontend/matterviz-viewer/pnpm-workspace.yaml b/frontend/matterviz-viewer/pnpm-workspace.yaml index 50351d37..53859288 100644 --- a/frontend/matterviz-viewer/pnpm-workspace.yaml +++ b/frontend/matterviz-viewer/pnpm-workspace.yaml @@ -1,4 +1,6 @@ +# Upstream MatterViz consumes svelte-widgets from GitHub. The lockfile pins both revisions. +blockExoticSubdeps: false allowBuilds: core-js: false matterviz: true - matterviz@0.4.2-multiwfn.d8719d12.r25.workbench1: false + svelte-widgets: true diff --git a/frontend/matterviz-viewer/src/AnalysisViewport.svelte b/frontend/matterviz-viewer/src/AnalysisViewport.svelte new file mode 100644 index 00000000..c6982132 --- /dev/null +++ b/frontend/matterviz-viewer/src/AnalysisViewport.svelte @@ -0,0 +1,65 @@ + + + + + + + + {#if surface} + surfaceSelection = value} onready={fit} /> + {:else if topology} + topologySelection = value} /> + {/if} + + diff --git a/frontend/matterviz-viewer/src/App.svelte b/frontend/matterviz-viewer/src/App.svelte index 261781e3..2e363711 100644 --- a/frontend/matterviz-viewer/src/App.svelte +++ b/frontend/matterviz-viewer/src/App.svelte @@ -1,116 +1,105 @@ - -
+
@@ -1860,58 +715,18 @@ onchange={show_result} />
{#if activeResult === 'scene'} - - -
- -
- - - - - - -
- -
- - - - -
- - - -
- - {#if orbital_selection_available()}{/if} - - {#if interaction_legend()}{/if} - - - {#if topologyResult}{/if} -
- {/if} - {#if activeResult === 'scene'} - + {#if orbital_selection_available()} + + {/if} {$t("Quantitative surface results...")} - { openMenu = undefined; surfacePanelOpen = false; topologyPanelOpen = true; inspectorOpen = false; orbitalPanelOpen = false }}>{$t("AIM critical points and paths...")} + { openMenu = undefined; surfacePanelOpen = surfaceActive = false; topologyPanelOpen = true; topologyActive = Boolean(topologyResult); orbitalPanelOpen = false }}>{$t("AIM critical points and paths...")} - {#if active_plot && !active_plot.native} - + {/if} - + {#if updaterBuildEnabled && updateStatus?.visible} {/if}
- {#if advancedStructure && manifest.periodic?.enabled && activeResult === 'scene'} - - {/if} -
-
- - - {#if inspectorOpen && !topologyPanelOpen && !surfacePanelOpen && !advancedStructure} - inspectorOpen = false} scene={repSceneSettings} errors={repErrors} /> - {:else if inspectorOpen && !topologyPanelOpen && !surfacePanelOpen} - isosurfaceSettings = { - ...next, - geometry_memory_budget_bytes: isosurfaceSettings.geometry_memory_budget_bytes, - }} - on_supercell_change={(value) => supercellScaling = value} - on_boundary_atoms_change={(value) => showImageAtoms = value} - on_unit_cell_change={set_inspector_unit_cell} - on_range_change={set_range} - on_layers={() => { open_panel('layers'); inspectorOpen = false }} - on_close={() => inspectorOpen = false} - /> - {/if} - - {#if surfacePanelOpen && surfaceResult} - surfacePanelOpen = false} onexport={export_surface} onfit={fit_surface} onconfirm={(value) => void confirm_surface(value)} onlog={(event) => void import_surface_log(event)} onclearlog={clear_surface_log} /> - {:else if topologyPanelOpen} - void request_topology()} onclose={() => topologyPanelOpen = false} onexport={export_topology} /> - {/if} -
- {#if advancedStructure}
{$t("Editing source structure. Atom and bond edits apply to all Reps.")}
{/if} -
- {#if structure} - report_error(new Error(message))} - on_selected_bond_context={open_bond_context_menu} - show_atom_tooltip={false} - measure_selection_policy={{ - distance: { max_sites: 2, overflow: 'restart' }, - angle: { max_sites: 4, overflow: 'reject' }, - }} - measure_geometry="ordered" - show_atom_legend={advancedStructure || topologyActive || surfaceActive} - show_controls={advancedStructure ? "always" : "never"} - allow_file_drop={false} - topology_view={topologyActive && Boolean(topologyResult)} - surface_view={surfaceActive && Boolean(surfaceResult)} - scene_children={topologyScene} - /> - {:else if !loading} -
{$t("No structure is available in this session.")}
- {/if} - {#if bondContextMenu && manifest.bondAnalysis?.methods} - - {#if loading || measurementSites.length || bondResults.length} -
- {#if loading} -
{format_message($locale, workingMessage)}
+ {#if loading || bondResults.length} +
+ {#if loading}
{format_message($locale, workingMessage)}
{/if} + {#each bondResults as result (result.key)}

{result.atoms} · {result.method} {result.value.toPrecision(6)}

{/each} +
{/if} - { measuredSites = []; repMeasurement = undefined }} - on_remove_bond={(key) => bondResults = bondResults.filter((result) => result.key !== key)} /> -
- {/if} -
- +
{#if orbital_selection_available() && orbitalPanelOpen}
{/if} - {#each plots as plot (plot.id)}
@@ -2252,141 +882,6 @@ {savingResult ? $t('Exporting...') : importingPlot ? $t('Opening plot...') : errorMessage || format_message($locale, status)} {active_plot ? $t('2D plot') : $t('{count} volume(s)', { count: volumetricData?.length || 0 })} - - {#if layerOpen} - - {/if} - {#if logOpen} {/if} - - {#if activeResult === 'scene' && !topologyActive && !surfaceActive && espExtremaOpen && esp_pair()} + {#if activeResult === 'scene' && !topologyActive && !surfaceActive && espExtremaOpen && espPair} {/if} - {#if updaterBuildEnabled && updateStatus?.visible} updateStatus = status} onclose={() => updateOpen = false} /> {/if}
-{#snippet topologyScene()} - {#if surfaceActive && surfaceResult} - { if (surfaceFitPending) fit_surface() }} onselect={(selection) => { surfaceSelection = selection; surfacePanelOpen = true; topologyPanelOpen = false }} /> - {:else if topologyActive && topologyResult} - { topologySelection = selection; topologyPanelOpen = true }} /> - {:else if !advancedStructure && structure} - {#each representations.items.filter((rep) => rep.visible) as rep, order (rep.id)} - item.visible && item.source.kind === 'volume').length))} - onmeasure={measure_rep} oncontext={open_bond_context_menu} onerror={report_rep_error} oncolorrange={report_rep_color_range} /> - {/each} - {/if} -{/snippet} - -{#snippet repSceneSettings()} -

{$t("Camera & display")}

- - - - - -

{$t("Lighting")}

- - {#each [{ key: 'ambient_light', label: 'Ambient light', fallback: 0.72 }, { key: 'directional_light', label: 'Directional light', fallback: 1.2 }, { key: 'fill_light', label: 'Fill light', fallback: 0.38 }, { key: 'rim_light', label: 'Rim light', fallback: 0.24 }] as control} - - {/each} -

{$t("Scene lighting is shared. Set opacity and reflection separately for each Rep.")}

-{/snippet} - diff --git a/frontend/matterviz-viewer/src/ColorScaleEditor.svelte b/frontend/matterviz-viewer/src/ColorScaleEditor.svelte deleted file mode 100644 index 37549e32..00000000 --- a/frontend/matterviz-viewer/src/ColorScaleEditor.svelte +++ /dev/null @@ -1,76 +0,0 @@ - - -
- - -
0%100%
- {#if custom} - -

{$t('Load a preset or edit color stops. 0% is the minimum; 100% is the maximum.')}

-
- {#each value.stops as stop, index} -
- color(event, index)} /> - color(event, index)} /> - - -
- {/each} -
- - {#if error}{/if} - {/if} -
- - diff --git a/frontend/matterviz-viewer/src/EspLegend.svelte b/frontend/matterviz-viewer/src/EspLegend.svelte deleted file mode 100644 index c85d7839..00000000 --- a/frontend/matterviz-viewer/src/EspLegend.svelte +++ /dev/null @@ -1,228 +0,0 @@ - - - - - diff --git a/frontend/matterviz-viewer/src/FieldPlot2D.svelte b/frontend/matterviz-viewer/src/FieldPlot2D.svelte index 3b06f2c2..4654dc34 100644 --- a/frontend/matterviz-viewer/src/FieldPlot2D.svelte +++ b/frontend/matterviz-viewer/src/FieldPlot2D.svelte @@ -98,7 +98,7 @@ {padding} user_content={user_content} legend={SCIENTIFIC_PLOT_LEGEND} - controls={{ show: true }} + show_controls="always" fullscreen_toggle={true} pan={{ enabled: true }} /> diff --git a/frontend/matterviz-viewer/src/FrequencyViewer.svelte b/frontend/matterviz-viewer/src/FrequencyViewer.svelte index 2c1f391b..ecbe892c 100644 --- a/frontend/matterviz-viewer/src/FrequencyViewer.svelte +++ b/frontend/matterviz-viewer/src/FrequencyViewer.svelte @@ -101,6 +101,7 @@ {#key data} { error = event.error_msg ?? 'Unable to display this normal mode.' }} /> diff --git a/frontend/matterviz-viewer/src/MeasurementReadout.svelte b/frontend/matterviz-viewer/src/MeasurementReadout.svelte deleted file mode 100644 index 8dfa3aa1..00000000 --- a/frontend/matterviz-viewer/src/MeasurementReadout.svelte +++ /dev/null @@ -1,62 +0,0 @@ - - -{#if sites.length && (mode === 'distance' || mode === 'angle')} -
- {$t(geometry?.name ?? 'Selected atoms')} - {names} - {#if geometry} - {geometry.value === null || !Number.isFinite(geometry.value) ? $t('Undefined') : `${geometry.value.toFixed(4)} ${geometry.unit}`} - {#if geometry.direct !== undefined}{$t("Direct:")} {geometry.direct.toFixed(4)} Å{/if} - {/if} - -
-{/if} -{#each bonds as result (result.key)} -
- {result.method} - {result.atoms} - {result.value.toFixed(6)} - -
-{/each} - - diff --git a/frontend/matterviz-viewer/src/MultiwfnPlotView.svelte b/frontend/matterviz-viewer/src/MultiwfnPlotView.svelte index b94c5f1e..7c5d2cea 100644 --- a/frontend/matterviz-viewer/src/MultiwfnPlotView.svelte +++ b/frontend/matterviz-viewer/src/MultiwfnPlotView.svelte @@ -45,7 +45,7 @@ label: line.label, style: { color: line.color, dash: line.dash === 'dash' ? '6 4' : undefined }, annotation: line.label ? { text: line.label } : undefined, - y_axis: line.axis === 'y2' ? 'y2' : 'y1', + y_axis: line.axis === 'y2' ? 'y2' : 'y', })) as RefLine[] let panels = $state(untrack(() => artifact.version === 1 ? v1_artifact.panels.map((panel) => ({ @@ -94,16 +94,16 @@ diff --git a/frontend/matterviz-viewer/src/PlotSceneView.svelte b/frontend/matterviz-viewer/src/PlotSceneView.svelte index f5bde68f..03fab5b9 100644 --- a/frontend/matterviz-viewer/src/PlotSceneView.svelte +++ b/frontend/matterviz-viewer/src/PlotSceneView.svelte @@ -115,7 +115,7 @@ {:else if route === 'binned-scatter'} {:else} - + {/if} diff --git a/frontend/matterviz-viewer/src/RepAppearance.svelte b/frontend/matterviz-viewer/src/RepAppearance.svelte deleted file mode 100644 index 4e26c898..00000000 --- a/frontend/matterviz-viewer/src/RepAppearance.svelte +++ /dev/null @@ -1,30 +0,0 @@ - - - - {@render children()} - diff --git a/frontend/matterviz-viewer/src/RepInspector.svelte b/frontend/matterviz-viewer/src/RepInspector.svelte deleted file mode 100644 index a8dbf85a..00000000 --- a/frontend/matterviz-viewer/src/RepInspector.svelte +++ /dev/null @@ -1,156 +0,0 @@ - - - diff --git a/frontend/matterviz-viewer/src/RepLayer.svelte b/frontend/matterviz-viewer/src/RepLayer.svelte deleted file mode 100644 index 2b70ca91..00000000 --- a/frontend/matterviz-viewer/src/RepLayer.svelte +++ /dev/null @@ -1,85 +0,0 @@ - - -{#if !data.error} - - {#if rep.source.kind === 'structure' && data.atoms} - - {:else if rep.source.kind === 'volume'} - onerror(rep.id, message)} oncolorrange={(range) => oncolorrange?.(rep.id, range)} /> - {/if} - - {#if rep.periodic.showCell && valid_cell(cell)} - - {/if} -{/if} diff --git a/frontend/matterviz-viewer/src/RepPeriodicControls.svelte b/frontend/matterviz-viewer/src/RepPeriodicControls.svelte deleted file mode 100644 index dd976838..00000000 --- a/frontend/matterviz-viewer/src/RepPeriodicControls.svelte +++ /dev/null @@ -1,65 +0,0 @@ - - -
- -

{$t('Fractional ranges follow a, b and c. For example, −0.5 to 1.5 shows two cells centered on the original cell.')}

-
- {$t('Axis')}{$t('From')}{$t('To')} - {#each ['a', 'b', 'c'] as axis, index} - - - - {/each} -
- {#if structure} - - {/if} - -
{$t('Translation vectors')}Å
- - {#if custom || sourceCell} -
- xyz - {#each ['a', 'b', 'c'] as axis, row} - {axis} - {#each [0, 1, 2] as column} - - {/each} - {/each} -
- {:else} -

{$t('This source has no periodic cell. Enter custom vectors to repeat it.')}

- {/if} -

{$t('Custom vectors translate copies without stretching atoms or the volume grid. Source data stays unchanged.')}

- {#if error}{/if} - -
diff --git a/frontend/matterviz-viewer/src/RepVolume.svelte b/frontend/matterviz-viewer/src/RepVolume.svelte deleted file mode 100644 index 820e2919..00000000 --- a/frontend/matterviz-viewer/src/RepVolume.svelte +++ /dev/null @@ -1,38 +0,0 @@ - - - - - oncolorrange?.(ranges[0])} /> - - diff --git a/frontend/matterviz-viewer/src/SlicePanel.svelte b/frontend/matterviz-viewer/src/SlicePanel.svelte deleted file mode 100644 index b4cd14e1..00000000 --- a/frontend/matterviz-viewer/src/SlicePanel.svelte +++ /dev/null @@ -1,199 +0,0 @@ - - - - - diff --git a/frontend/matterviz-viewer/src/SurfaceAnalysisPanel.svelte b/frontend/matterviz-viewer/src/SurfaceAnalysisPanel.svelte index 19da881b..3ea8e0f3 100644 --- a/frontend/matterviz-viewer/src/SurfaceAnalysisPanel.svelte +++ b/frontend/matterviz-viewer/src/SurfaceAnalysisPanel.svelte @@ -1,6 +1,6 @@ diff --git a/frontend/matterviz-viewer/src/TopologyPanel.svelte b/frontend/matterviz-viewer/src/TopologyPanel.svelte index 75de1e4f..43e1ef62 100644 --- a/frontend/matterviz-viewer/src/TopologyPanel.svelte +++ b/frontend/matterviz-viewer/src/TopologyPanel.svelte @@ -1,6 +1,6 @@ diff --git a/frontend/matterviz-viewer/src/UpdateModal.svelte b/frontend/matterviz-viewer/src/UpdateModal.svelte index a3a5b175..24048840 100644 --- a/frontend/matterviz-viewer/src/UpdateModal.svelte +++ b/frontend/matterviz-viewer/src/UpdateModal.svelte @@ -1,5 +1,5 @@ - - - - diff --git a/frontend/matterviz-viewer/src/atom-style.ts b/frontend/matterviz-viewer/src/atom-style.ts deleted file mode 100644 index d099df4e..00000000 --- a/frontend/matterviz-viewer/src/atom-style.ts +++ /dev/null @@ -1,57 +0,0 @@ -export type AtomStyle = 'current' | 'goodsell' | 'edgy' | 'glass' | 'metallic' | 'matte' - -export type AtomStyleSettings = { - atom_style?: AtomStyle - atom_roughness?: number - atom_metalness?: number - atom_opacity?: number - atom_outline?: number - atom_outline_width?: number -} - -export const ATOM_STYLE_PRESETS: ReadonlyArray<{ value: AtomStyle; label: string; roughness: number; metalness: number; opacity: number; outline: number; outlineWidth: number }> = [ - { value: 'current', label: 'Balanced', roughness: .5, metalness: .07, opacity: 1, outline: .10, outlineWidth: .6 }, - { value: 'goodsell', label: 'Goodsell', roughness: .7, metalness: 0, opacity: 1, outline: .10, outlineWidth: .6 }, - { value: 'edgy', label: 'Edgy', roughness: .25, metalness: 0, opacity: 1, outline: .50, outlineWidth: .9 }, - { value: 'glass', label: 'Glass', roughness: .05, metalness: 0, opacity: .55, outline: .05, outlineWidth: .6 }, - { value: 'metallic', label: 'Metallic', roughness: .28, metalness: .80, opacity: 1, outline: .05, outlineWidth: .6 }, - { value: 'matte', label: 'Matte', roughness: .92, metalness: 0, opacity: 1, outline: 0, outlineWidth: .6 }, -] - -const clamp = (v: unknown, min: number, max: number): number | undefined => { - const n = typeof v === 'number' ? v : typeof v === 'string' && v.trim() ? Number(v) : NaN - return Number.isFinite(n) ? Math.min(max, Math.max(min, n)) : undefined -} - -export const normalize_atom_style = (value: unknown): AtomStyleSettings => { - if (!value || typeof value !== 'object' || Array.isArray(value)) return {} - const row = value as Record - const result: AtomStyleSettings = {} - const style = row.atomStyle ?? row.atom_style - if (ATOM_STYLE_PRESETS.some((p) => p.value === style)) result.atom_style = style as AtomStyle - const roughness = clamp(row.atomRoughness ?? row.atom_roughness, 0, 1) - const metalness = clamp(row.atomMetalness ?? row.atom_metalness, 0, 1) - const opacity = clamp(row.atomOpacity ?? row.atom_opacity, 0, 1) - const outline = clamp(row.atomOutline ?? row.atom_outline, 0, 1) - const width = clamp(row.atomOutlineWidth ?? row.atom_outline_width, 0, 1) - if (roughness !== undefined) result.atom_roughness = roughness - if (metalness !== undefined) result.atom_metalness = metalness - if (opacity !== undefined) result.atom_opacity = opacity - if (outline !== undefined) result.atom_outline = outline - if (width !== undefined) result.atom_outline_width = width - return result -} - -export const apply_atom_style = (scene: Record, style: AtomStyle): Record => { - const preset = ATOM_STYLE_PRESETS.find((p) => p.value === style) - // TMIM's original atom renderer used MeshStandardMaterial for every finish; - // preserve that shading model while varying the PBR parameters. - const material = 'pbr' - return preset ? { ...scene, atom_style: style, atom_material: material, atom_roughness: preset.roughness, atom_metalness: preset.metalness, atom_opacity: preset.opacity, atom_outline: preset.outline, atom_outline_width: preset.outlineWidth } : scene -} - -export const atom_style_values = (scene: Record) => { - const normalized = normalize_atom_style(scene) - const preset = ATOM_STYLE_PRESETS.find((p) => p.value === normalized.atom_style) - return { ...preset, ...normalized } -} diff --git a/frontend/matterviz-viewer/src/camera.ts b/frontend/matterviz-viewer/src/camera.ts deleted file mode 100644 index 6a4bb595..00000000 --- a/frontend/matterviz-viewer/src/camera.ts +++ /dev/null @@ -1,189 +0,0 @@ -import type { CameraProjection, Vec3 } from 'matterviz' - -export type CameraPose = { - position: Vec3 - target: Vec3 - up: Vec3 - projection: CameraProjection - zoom?: number -} - -/** A fixed-step rotation in the camera's screen coordinate system. */ -export type CameraDirection = 'up' | 'down' | 'left' | 'right' | 'clockwise' | 'counterclockwise' -export type CameraStepKind = 'rotation' | 'pan' | 'zoom' - -export type CameraStateUpdate = { - camera_position?: Vec3 - camera_target?: Vec3 - camera_up?: Vec3 - camera_zoom?: number -} - -export type CurrentCameraState = CameraStateUpdate & { - camera_projection?: 'perspective' | 'orthographic' -} - -const EPSILON = 1e-10 - -const same_vec3 = (current: Vec3 | undefined, next: Vec3 | undefined): boolean => - current === next || - Boolean( - current && - next && - current.every((value, index) => Math.abs(value - next[index]) <= 1e-12), - ) - -export const camera_update_matches = ( - current: CurrentCameraState, - update: CameraStateUpdate, -): boolean => { - const nextProjection = update.camera_zoom !== undefined ? 'orthographic' : 'perspective' - return ( - (!update.camera_position || same_vec3(current.camera_position, update.camera_position)) && - (!update.camera_target || same_vec3(current.camera_target, update.camera_target)) && - (!update.camera_up || same_vec3(current.camera_up, update.camera_up)) && - current.camera_zoom === update.camera_zoom && - current.camera_projection === nextProjection - ) -} - -const STEP_LIMITS: Record = { - rotation: [0.1, 180], - pan: [0.001, 100], - zoom: [0.1, 500], -} - -export const normalize_camera_step = (value: unknown, kind: CameraStepKind): number | undefined => { - if (value === '' || value === null || value === undefined) return undefined - const numeric = typeof value === 'number' ? value : Number(value) - if (!Number.isFinite(numeric)) return undefined - const [minimum, maximum] = STEP_LIMITS[kind] - return Math.min(maximum, Math.max(minimum, numeric)) -} - -const finite_vec3 = (value: unknown): Vec3 | undefined => { - if (!Array.isArray(value) || value.length !== 3) return undefined - const vector = value.map(Number) - return vector.every(Number.isFinite) ? vector as Vec3 : undefined -} - -const add = (left: Vec3, right: Vec3): Vec3 => left.map((value, idx) => value + right[idx]) as Vec3 -const subtract = (left: Vec3, right: Vec3): Vec3 => left.map((value, idx) => value - right[idx]) as Vec3 -const scale = (vector: Vec3, factor: number): Vec3 => vector.map((value) => value * factor) as Vec3 -const dot = (left: Vec3, right: Vec3): number => left.reduce((sum, value, idx) => sum + value * right[idx], 0) -const cross = (left: Vec3, right: Vec3): Vec3 => [ - left[1] * right[2] - left[2] * right[1], - left[2] * right[0] - left[0] * right[2], - left[0] * right[1] - left[1] * right[0], -] -const length = (vector: Vec3): number => Math.hypot(...vector) - -const normalize = (vector: Vec3): Vec3 | undefined => { - const magnitude = length(vector) - return Number.isFinite(magnitude) && magnitude > EPSILON ? scale(vector, 1 / magnitude) : undefined -} - -const fallback_up = (back: Vec3): Vec3 => { - const candidates: Vec3[] = [[0, 1, 0], [1, 0, 0], [0, 0, 1]] - const seed = candidates.reduce((best, candidate) => - Math.abs(dot(candidate, back)) < Math.abs(dot(best, back)) ? candidate : best) - return normalize(subtract(seed, scale(back, dot(seed, back)))) ?? [0, 1, 0] -} - -export const normalize_camera_pose = (value: Partial): CameraPose | undefined => { - const position = finite_vec3(value.position) - const target = finite_vec3(value.target) - const rawUp = finite_vec3(value.up) ?? [0, 1, 0] - const projection = value.projection === 'perspective' || value.projection === 'orthographic' - ? value.projection - : undefined - if (!position || !target || !projection) return undefined - const back = normalize(subtract(position, target)) - if (!back) return undefined - // Project the supplied up vector into the plane perpendicular to the view - // direction. This keeps the stored pose itself orthonormal, rather than - // relying on camera_basis to repair it only at call sites. - const up = normalize(subtract(rawUp, scale(back, dot(rawUp, back)))) ?? fallback_up(back) - const zoom = Number.isFinite(value.zoom) && Number(value.zoom) > 0 ? Number(value.zoom) : undefined - return { position, target, up, projection, ...(zoom !== undefined ? { zoom } : {}) } -} - -export const camera_basis = (pose: CameraPose): { right: Vec3; up: Vec3; back: Vec3 } => { - const normalized = normalize_camera_pose(pose) - if (!normalized) return { right: [1, 0, 0], up: [0, 1, 0], back: [0, 0, 1] } - const back = normalize(subtract(normalized.position, normalized.target)) ?? [0, 0, 1] - const right = normalize(cross(normalized.up, back)) ?? [1, 0, 0] - const up = normalize(cross(back, right)) ?? normalized.up - return { right, up, back } -} - -const rodrigues = (vector: Vec3, axis: Vec3, radians: number): Vec3 => { - const cosine = Math.cos(radians) - const sine = Math.sin(radians) - return add( - add(scale(vector, cosine), scale(cross(axis, vector), sine)), - scale(axis, dot(axis, vector) * (1 - cosine)), - ) -} - -export const rotate_camera = (pose: CameraPose, direction: CameraDirection, degrees: number): CameraPose => { - const normalized = normalize_camera_pose(pose) - if (!normalized || !Number.isFinite(degrees)) return pose - const basis = camera_basis(normalized) - let rotationAxis: Vec3 - let sign: 1 | -1 - switch (direction) { - // Positive rotation around screen-right makes fixed points move upward. - case 'up': rotationAxis = basis.right; sign = 1; break - case 'down': rotationAxis = basis.right; sign = -1; break - // Positive right-handed rotation around screen-up makes fixed points move - // left, hence the opposite sign for a visible rightward move. - case 'left': rotationAxis = basis.up; sign = 1; break - case 'right': rotationAxis = basis.up; sign = -1; break - // Looking toward the target, positive rotation around camera-back carries - // screen-up toward screen-left, i.e. a clockwise visible roll. - case 'clockwise': rotationAxis = basis.back; sign = 1; break - case 'counterclockwise': rotationAxis = basis.back; sign = -1; break - default: return pose - } - const radians = sign * degrees * Math.PI / 180 - const offset = subtract(normalized.position, normalized.target) - const rotatedOffset = rodrigues(offset, rotationAxis, radians) - const rotatedUp = rodrigues(normalized.up, rotationAxis, radians) - return normalize_camera_pose({ - ...normalized, - position: add(normalized.target, rotatedOffset), - up: rotatedUp, - }) ?? normalized -} - -export const pan_camera = (pose: CameraPose, horizontal: number, vertical: number): CameraPose => { - const normalized = normalize_camera_pose(pose) - if (!normalized || !Number.isFinite(horizontal) || !Number.isFinite(vertical)) return pose - const { right, up } = camera_basis(normalized) - const delta = add(scale(right, horizontal), scale(up, vertical)) - return { ...normalized, position: add(normalized.position, delta), target: add(normalized.target, delta) } -} - -export const zoom_camera = ( - pose: CameraPose, - percent: number, - direction: 'in' | 'out', -): CameraPose => { - const normalized = normalize_camera_pose(pose) - if (!normalized || !Number.isFinite(percent) || percent <= 0) return pose - const factor = 1 + Math.min(500, percent) / 100 - if (normalized.projection === 'orthographic') { - if (normalized.zoom === undefined) return normalized - const zoom = direction === 'in' ? normalized.zoom * factor : normalized.zoom / factor - return { ...normalized, zoom: Math.min(1e6, Math.max(1e-4, zoom)) } - } - const offset = subtract(normalized.position, normalized.target) - const distance = length(offset) - if (!Number.isFinite(distance) || distance <= EPSILON) return normalized - const nextDistance = direction === 'in' ? distance / factor : distance * factor - return { - ...normalized, - position: add(normalized.target, scale(offset, Math.min(1e6, Math.max(1e-4, nextDistance)) / distance)), - } -} diff --git a/frontend/matterviz-viewer/src/color-scale.ts b/frontend/matterviz-viewer/src/color-scale.ts deleted file mode 100644 index b535ad04..00000000 --- a/frontend/matterviz-viewer/src/color-scale.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { normalize_color_stops, type ColorStop } from 'matterviz/colors/stops' -import { trans_flag_color_css } from './esp.ts' - -export type ColorScale = { preset: string; stops: ColorStop[] } -// D3 palettes sampled at eighths: presets are editable sRGB control points, -// using the same piecewise interpolation as custom scales and the legend. -export const COLOR_SCALE_PRESETS = [ - { name: 'TransFlag', colors: ['#f5a9b8', '#ffffff', '#5bcefa'] }, - { name: 'Viridis', colors: ['#440154', '#472d7b', '#3b528b', '#2c728e', '#21918c', '#28ae80', '#5ec962', '#addc30', '#fde725'] }, - { name: 'RdBu', colors: ['#67001f', '#b82d35', '#e48268', '#faccb4', '#f2efee', '#bfdceb', '#6bacd0', '#2a71ae', '#053061'] }, - { name: 'Turbo', colors: ['#23171b', '#4569ee', '#26bce1', '#3ff393', '#95fb51', '#ecd12e', '#ff821d', '#cb2f0d', '#900c00'] }, - { name: 'Plasma', colors: ['#0d0887', '#4c02a1', '#7e03a8', '#aa2395', '#cc4778', '#e66c5c', '#f89540', '#fdc527', '#f0f921'] }, - { name: 'Inferno', colors: ['#000004', '#210c4a', '#57106e', '#8a226a', '#bc3754', '#e45a31', '#f98e09', '#f9cb35', '#fcffa4'] }, - { name: 'Magma', colors: ['#000004', '#1d1147', '#51127c', '#832681', '#b73779', '#e75263', '#fc8961', '#fec488', '#fcfdbf'] }, - { name: 'Cividis', colors: ['#002051', '#11366c', '#3c4d6e', '#62646f', '#7f7c75', '#9a9478', '#bbaf71', '#e2cb5c', '#fdea45'] }, - { name: 'RdYlBu', colors: ['#a50026', '#dd4030', '#f88d52', '#fed284', '#faf8c1', '#d1ebef', '#90c2dd', '#5382bb', '#313695'] }, - { name: 'Spectral', colors: ['#9e0142', '#db494a', '#f88e53', '#fed281', '#fbf8b0', '#d5ee9f', '#89cfa5', '#4696b3', '#5e4fa2'] }, - { name: 'PiYG', colors: ['#8e0152', '#c9378a', '#e795c3', '#f9d4e9', '#f5f3ef', '#d8efbb', '#9bce64', '#5a9c2b', '#276419'] }, - { name: 'BrBG', colors: ['#543005', '#985e15', '#cea156', '#efddb0', '#eef1ea', '#b3e1db', '#5bb2a8', '#12736a', '#003c30'] }, - { name: 'PuOr', colors: ['#2d004b', '#5f3d8f', '#998ebf', '#cecde4', '#f3eeea', '#fdd5a0', '#ee9d3d', '#be630b', '#7f3b08'] }, - { name: 'Cool', colors: ['#6e40aa', '#5c5ace', '#417de0', '#27a3dc', '#1ac7c2', '#21e39b', '#40f373', '#73f65a', '#aff05b'] }, - { name: 'Warm', colors: ['#6e40aa', '#a03db3', '#d23ea7', '#f9488a', '#ff5e63', '#ff7f41', '#efa72f', '#cdcf37', '#aff05b'] }, - { name: 'RdYlGn', colors: ['#a50026', '#dd4030', '#f88d52', '#fed281', '#f9f7ae', '#cbe984', '#85cb67', '#30a054', '#006837'] }, - { name: 'Greys', colors: ['#ffffff', '#efefef', '#d8d8d8', '#bbbbbb', '#979797', '#737373', '#505050', '#262626', '#000000'] }, -] - -export const preset_color_scale = (name: string): ColorScale => { - const preset = COLOR_SCALE_PRESETS.find((item) => `interpolate${item.name}` === name) ?? COLOR_SCALE_PRESETS[1] - return { preset: `interpolate${preset.name}`, stops: preset.colors.map((color, index) => ({ color, position: index / (preset.colors.length - 1) })) } -} - -export const normalize_color_scale = (value: unknown): ColorScale => { - if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Invalid color scale') - const row = value as Record, stops = normalize_color_stops(row.stops) - const preset = typeof row.preset === 'string' && COLOR_SCALE_PRESETS.some((item) => `interpolate${item.name}` === row.preset) ? row.preset : 'custom' - // A named preset must describe the actual points; edited/imported points are custom. - const expected = preset_color_scale(preset).stops - return { preset: preset !== 'custom' && expected.length === stops.length && stops.every((stop, index) => stop.position === expected[index].position && stop.color === expected[index].color) ? preset : 'custom', stops } -} - -/** Preserve physical-zero anchoring when migrating the old pink/white/blue map. */ -export const legacy_color_scale = (colormap = 'interpolateViridis', range?: [number, number]): ColorScale => { - const scale = preset_color_scale(colormap) - if (colormap !== 'interpolateTransFlag' || !range || !range.every(Number.isFinite)) return scale - const [lower, upper] = [...range].sort((a, b) => a - b) - const positions = lower < 0 && upper > 0 ? [0, -lower / (upper - lower), 1] : [0, 1] - return normalize_color_scale({ preset: scale.preset, stops: positions.map((position) => ({ position, color: trans_flag_color_css(lower + position * (upper - lower), lower, upper) })) }) -} - -type VolumeColorScale = { colorScale?: ColorScale; colormap?: string; color_range?: [number, number]; color_stops?: ColorStop[] } -export const volume_color_scale = (volume: VolumeColorScale): ColorScale => - volume.colorScale ?? (volume.color_stops ? normalize_color_scale({ stops: volume.color_stops }) : legacy_color_scale(volume.colormap, volume.color_range)) - -/** Defer legacy zero-anchored automatic scales until the renderer knows their range. */ -export const migrate_color_scale = (volume: VolumeColorScale, rendered_range?: [number, number]): ColorScale | undefined => { - if (!volume.colorScale && !volume.color_stops && volume.colormap === 'interpolateTransFlag' && !volume.color_range && !rendered_range) return undefined - return volume_color_scale({ ...volume, color_range: volume.color_range ?? rendered_range }) -} diff --git a/frontend/matterviz-viewer/src/esp.ts b/frontend/matterviz-viewer/src/esp.ts index 1dec7c73..1c5a254d 100644 --- a/frontend/matterviz-viewer/src/esp.ts +++ b/frontend/matterviz-viewer/src/esp.ts @@ -1,4 +1,4 @@ -import type { IsosurfaceLayer, VolumetricData } from 'matterviz' +import type { VolumetricData } from 'matterviz/isosurface' import type { ManifestEntry } from './manifest' /** Hartree to kcal/mol for one electron. */ @@ -11,9 +11,8 @@ export const normalize_esp_volume = (volume: VolumetricData, entry: ManifestEntr const scale = (value: number): number => value / KCAL_PER_HARTREE return { ...volume, - grid: Array.isArray(volume.grid) - ? volume.grid.map(plane => plane.map(row => row.map(scale))) - : { ...volume.grid, data: volume.grid.data.map(scale) }, + values: volume.values.map(scale), + units: 'hartree/e', data_range: { min: scale(volume.data_range.min), max: scale(volume.data_range.max), abs_max: scale(volume.data_range.abs_max), mean: scale(volume.data_range.mean), @@ -34,15 +33,15 @@ export const ESP_COLORMAP = 'interpolateTransFlag' export const surface_colormap = ( colorSource: ManifestEntry | undefined, - fallback: NonNullable, -): NonNullable => + fallback: string, +): string => colorSource?.analysisKind === 'esp-potential' ? ESP_COLORMAP : fallback export type Vec3 = [number, number, number] export type LegendPosition = { left: number; top: number } export type EspVolume = Partial | Record export type EspPair = { densityIdx: number; potentialIdx: number } -type EspLayerLink = Pick +type EspLayerLink = { volume_idx?: number; color_volume_idx?: number } type GridCompatibility = (leftIdx: number, rightIdx: number) => boolean export const find_declared_esp_pair = ( @@ -176,6 +175,10 @@ const as_grid = (volume: unknown): unknown[][][] | undefined => { /** Return validated dimensions without assuming a particular parser layout. */ export const volume_dimensions = (volume: unknown): Vec3 | undefined => { + const flat = volume as Partial | undefined + if (flat?.values instanceof Float64Array && flat.dims?.length === 3 && + flat.dims.every(n => Number.isSafeInteger(n) && n > 0) && + flat.values.length === flat.dims[0] * flat.dims[1] * flat.dims[2]) return flat.dims const candidate = (volume as { grid_dims?: unknown })?.grid_dims const grid = as_grid(volume) if (!grid) return undefined @@ -212,6 +215,8 @@ const vectors_match = (left: Vec3, right: Vec3, tolerance = 1e-8): boolean => left.every((value, index) => Math.abs(value - right[index]) <= tolerance) const grid_value = (volume: unknown, x: number, y: number, z: number): number => { + const flat = volume as Partial + if (flat?.values && flat.dims) return flat.values[(x * flat.dims[1] + y) * flat.dims[2] + z] const grid = as_grid(volume) const value = grid?.[x]?.[y]?.[z] return Number(value) diff --git a/frontend/matterviz-viewer/src/frequency.ts b/frontend/matterviz-viewer/src/frequency.ts index 0aa1e5f7..5c5270cd 100644 --- a/frontend/matterviz-viewer/src/frequency.ts +++ b/frontend/matterviz-viewer/src/frequency.ts @@ -1,7 +1,7 @@ import { element_data } from 'matterviz/element' -import { bonding_strategies, make_site, type Molecule } from 'matterviz/structure' +import { compute_bonds, normalize_structure_bond, make_site, type Molecule } from 'matterviz/structure' import type { Vec3 } from 'matterviz/math' -import type { TrajectoryFrame, TrajectoryType } from 'matterviz/trajectory' +import { encode_frame, sync_run, TrajectoryProperties, type TrajectoryFrame, type TrajectoryRun } from 'matterviz/trajectory' export const FREQUENCY_FILE_LIMIT = 16 * 1024 * 1024 export const FREQUENCY_FRAMES = 48 @@ -82,8 +82,8 @@ export function read_frequency_cjson(text: string): FrequencyData { return { number: index + 1, frequency, displacement: components, ...(typeof ir === 'number' ? { ir } : {}) } }) // Infer bonds once at equilibrium with MatterViz, then keep them fixed throughout playback. - const bonds = bonding_strategies.compute_bonds({ sites }, 'electroneg_ratio') - .map(({ site_idx_1, site_idx_2, bond_order }) => bonding_strategies.normalize_structure_bond(site_idx_1, site_idx_2, bond_order ?? 1)) + const bonds = compute_bonds({ sites }, 'electroneg_ratio') + .map(({ site_idx_1, site_idx_2, bond_order }) => normalize_structure_bond(site_idx_1, site_idx_2, bond_order ?? 1)) const structure: Molecule = { sites, properties: { bonds } } return { structure, modes } } @@ -93,7 +93,7 @@ export function read_frequency_cjson(text: string): FrequencyData { * vectors retain their relative lengths: never divide cclib vibdisps by sqrt(mass). * The global scale makes amplitude the largest atomic excursion in Å. */ -export function frequency_trajectory(data: FrequencyData, modeIndex: number, amplitude = DEFAULT_FREQUENCY_AMPLITUDE): TrajectoryType { +export function frequency_trajectory(data: FrequencyData, modeIndex: number, amplitude = DEFAULT_FREQUENCY_AMPLITUDE): TrajectoryRun { const mode = data.modes[modeIndex] if (!mode) throw new Error('Select an available normal mode.') if (!Number.isFinite(amplitude) || amplitude <= 0 || amplitude > 2) { @@ -115,15 +115,14 @@ export function frequency_trajectory(data: FrequencyData, modeIndex: number, amp step: index, } } - return { - frames: [frame(0)], - total_frames: FREQUENCY_FRAMES, + return sync_run({ + label: `Normal mode ${mode.number}`, + provenance: { format: 'cclib CJSON' }, + properties: new TrajectoryProperties([], true), + warnings: [], + preview: frame(0), + frame_count: FREQUENCY_FRAMES, + read: index => encode_frame(frame(index)), metadata: { frequency_cm_1: mode.frequency, mode: mode.number, amplitude_angstrom: amplitude }, - frame_loader: { - load_frame: async (_data, index) => frame(index), - get_total_frames: async () => FREQUENCY_FRAMES, - build_frame_index: async () => [], - extract_plot_metadata: async () => [], - }, - } + }) } diff --git a/frontend/matterviz-viewer/src/lighting.ts b/frontend/matterviz-viewer/src/lighting.ts deleted file mode 100644 index bbba6410..00000000 --- a/frontend/matterviz-viewer/src/lighting.ts +++ /dev/null @@ -1,38 +0,0 @@ -export const LIGHTING_DEFAULTS = { ambient_light: 0.72, directional_light: 1.2 } as const -export const TMIM_LIGHTING_DEFAULTS = { - ambient_light: 1.25, directional_light: 1.55, fill_light: 0.85, rim_light: 0.42, -} as const -export type LightingKey = 'ambient_light' | 'directional_light' | 'fill_light' | 'rim_light' -export type LightingRig = 'default' | 'tmim' -export type SceneToneMapping = 'agx' | 'none' -export type LightingSettings = Partial> & { - lighting_rig?: LightingRig - scene_tone_mapping?: SceneToneMapping -} - -export const normalize_light_intensity = (value: unknown): number | undefined => { - const number = typeof value === 'number' - ? value - : typeof value === 'string' && value.trim() !== '' ? Number(value) : Number.NaN - return Number.isFinite(number) ? Math.min(4, Math.max(0, number)) : undefined -} - -/** Accept scene props and saved workbench names; absent fields retain the current lighting. */ -export const normalize_lighting = (value: unknown): LightingSettings => { - if (value === null || typeof value !== 'object' || Array.isArray(value)) return {} - const row = value as Record - const settings: LightingSettings = {} - const ambient = normalize_light_intensity(row.ambientLight ?? row.ambient_light) - const directional = normalize_light_intensity(row.directionalLight ?? row.directional_light) - const fill = normalize_light_intensity(row.fillLight ?? row.fill_light) - const rim = normalize_light_intensity(row.rimLight ?? row.rim_light) - if (ambient !== undefined) settings.ambient_light = ambient - if (directional !== undefined) settings.directional_light = directional - if (fill !== undefined) settings.fill_light = fill - if (rim !== undefined) settings.rim_light = rim - const rig = row.lightingRig ?? row.lighting_rig - if (rig === 'default' || rig === 'tmim') settings.lighting_rig = rig - const tone = row.sceneToneMapping ?? row.scene_tone_mapping - if (tone === 'agx' || tone === 'none') settings.scene_tone_mapping = tone - return settings -} diff --git a/frontend/matterviz-viewer/src/material.ts b/frontend/matterviz-viewer/src/material.ts deleted file mode 100644 index 027884c9..00000000 --- a/frontend/matterviz-viewer/src/material.ts +++ /dev/null @@ -1,198 +0,0 @@ -import type { IsosurfaceSettings } from 'matterviz' - -export type SurfaceAppearance = Partial> - -export const SURFACE_NUMBER_LIMITS = { - roughness: [0, 1], - metalness: [0, 1], - shininess: [1, 120], - specular: [0, 1], - halo: [0, 1], - outline: [0, 1], - outlineWidth: [0, 1], -} as const - -export type SurfaceNumber = keyof typeof SURFACE_NUMBER_LIMITS - -// Keep unset controls consistent with the bundled MatterViz renderer. -export const SURFACE_DEFAULTS = { - material: 'matte', - roughness: 0.7, - metalness: 0, - shininess: 18, - specular: 0.12, - wireframe: false, - flat_shading: false, - halo: 0, - outline: 0, - outlineWidth: 0.6, - transmode: 0, -} as const - -export const normalize_surface_number = (key: SurfaceNumber, value: unknown): number | undefined => { - const number = typeof value === 'number' - ? value - : typeof value === 'string' && value.trim() !== '' ? Number(value) : Number.NaN - if (!Number.isFinite(number)) return undefined - const [minimum, maximum] = SURFACE_NUMBER_LIMITS[key] - return Math.min(maximum, Math.max(minimum, number)) -} - -/** Read only appearance fields, without introducing defaults into older snapshots. */ -export const normalize_surface_appearance = (value: unknown): SurfaceAppearance => { - if (value === null || typeof value !== 'object' || Array.isArray(value)) return {} - const row = value as Record - const appearance: SurfaceAppearance = {} - if (row.material === 'matte' || row.material === 'glossy' || row.material === 'pbr' || row.material === 'unlit') { - appearance.material = row.material - } - for (const key of ['wireframe', 'flat_shading'] as const) { - if (typeof row[key] === 'boolean') appearance[key] = row[key] - } - for (const key of Object.keys(SURFACE_NUMBER_LIMITS) as SurfaceNumber[]) { - const number = normalize_surface_number(key, row[key]) - if (number !== undefined) appearance[key] = number - } - if (row.transmode === 0 || row.transmode === 1) appearance.transmode = row.transmode - return appearance -} - -export type SurfacePreset = 'matte' | 'soft-gloss' | 'satin' | 'unlit' - | 'diffuse' | 'goodsell' | 'edgy' | 'edgy-shiny' | 'ao-shiny' | 'ao-chalky' - | 'glass1' | 'glass-bubble' | 'edgy-glass' | 'brushed-metal' | 'metallic' | 'pbr' - -type SurfacePresetDefinition = { - value: SurfacePreset - label: string - description: string - group?: 'legacy' - appearance: Omit -} - -const SMOOTH_FINISH = { - wireframe: false, - flat_shading: false, - outline: 0, - outlineWidth: 0.6, - transmode: 0, -} as const - -export const SURFACE_PRESETS: ReadonlyArray = [ - { - value: 'matte', - label: 'Matte', - description: 'Diffuse shading with no specular highlights.', - appearance: { ...SMOOTH_FINISH, material: 'matte' }, - }, - { - value: 'soft-gloss', - label: 'Soft gloss', - description: 'Gentle highlights bring out the surface curvature.', - appearance: { ...SMOOTH_FINISH, material: 'glossy', shininess: 24, specular: 0.16 }, - }, - { - value: 'satin', - label: 'Satin', - description: 'A smooth, nonmetallic finish with broad highlights.', - appearance: { ...SMOOTH_FINISH, material: 'pbr', roughness: 0.48, metalness: 0 }, - }, - { - value: 'unlit', - label: 'Unlit color', - description: 'Colors stay independent of lighting and surface orientation.', - appearance: { ...SMOOTH_FINISH, material: 'unlit' }, - }, - // Original MaterialPanel combinations. Preserve their parameter values and - // familiar names, while keeping the existing four finishes as the primary set. - { - value: 'diffuse', label: 'Diffuse', group: 'legacy', - description: 'Diffuse shading with no specular highlights, like Matte.', - appearance: { ...SMOOTH_FINISH, material: 'matte', outline: 0, outlineWidth: 0.6, transmode: 0 }, - }, - { - value: 'goodsell', label: 'Goodsell', group: 'legacy', - description: 'The original smooth matte finish with no specular highlights.', - appearance: { - ...SMOOTH_FINISH, material: 'matte', roughness: 0.7, metalness: 0, shininess: 18, - specular: 0.12, outline: 0, outlineWidth: 0.6, transmode: 0, - }, - }, - { - value: 'edgy', label: 'Edgy', group: 'legacy', - description: 'Glossy highlights with a strong, broad dark rim.', - appearance: { ...SMOOTH_FINISH, material: 'glossy', shininess: 50, specular: 0.5, outline: 0.5, outlineWidth: 0.9, transmode: 0 }, - }, - { - value: 'edgy-shiny', label: 'EdgyShiny', group: 'legacy', - description: 'Bright, tight highlights with a pronounced dark rim.', - appearance: { ...SMOOTH_FINISH, material: 'glossy', shininess: 70, specular: 0.85, outline: 0.6, outlineWidth: 0.92, transmode: 0 }, - }, - { - value: 'ao-shiny', label: 'AOShiny', group: 'legacy', - description: 'Glossy shading with a subtle rim; the original name does not add ambient occlusion.', - appearance: { ...SMOOTH_FINISH, material: 'glossy', shininess: 45, specular: 0.55, outline: 0.15, outlineWidth: 0.7, transmode: 0 }, - }, - { - value: 'ao-chalky', label: 'AOChalky', group: 'legacy', - description: 'Soft highlights with a subtle rim; the original name does not add ambient occlusion.', - appearance: { ...SMOOTH_FINISH, material: 'glossy', shininess: 20, specular: 0.2, outline: 0.1, outlineWidth: 0.6, transmode: 0 }, - }, - { - value: 'glass1', label: 'Glass1', group: 'legacy', - description: 'Glossy highlights with stronger grazing edges on transparent layers.', - appearance: { ...SMOOTH_FINISH, material: 'glossy', shininess: 55, specular: 0.65, outline: 0.05, outlineWidth: 0.6, transmode: 1 }, - }, - { - value: 'glass-bubble', label: 'GlassBubble', group: 'legacy', - description: 'Bright, tight highlights with stronger edges on transparent layers.', - appearance: { ...SMOOTH_FINISH, material: 'glossy', shininess: 90, specular: 0.95, outline: 0.05, outlineWidth: 0.6, transmode: 1 }, - }, - { - value: 'edgy-glass', label: 'EdgyGlass', group: 'legacy', - description: 'Glossy shading and a broad dark rim with stronger edges on transparent layers.', - appearance: { ...SMOOTH_FINISH, material: 'glossy', shininess: 70, specular: 0.6, outline: 0.5, outlineWidth: 0.9, transmode: 1 }, - }, - { - value: 'brushed-metal', label: 'BrushedMetal', group: 'legacy', - description: 'A rough metallic finish with a subtle dark rim.', - appearance: { ...SMOOTH_FINISH, material: 'pbr', metalness: 0.75, roughness: 0.35, specular: 0.3, outline: 0.05, outlineWidth: 0.6, transmode: 0 }, - }, - { - value: 'metallic', label: 'Metallic', group: 'legacy', - description: 'A smooth metallic finish with a subtle dark rim.', - appearance: { ...SMOOTH_FINISH, material: 'pbr', metalness: 0.8, roughness: 0.28, specular: 0.3, outline: 0.05, outlineWidth: 0.6, transmode: 0 }, - }, - { - value: 'pbr', label: 'PBR', group: 'legacy', - description: 'A moderately rough finish with mild metalness and rim contrast.', - appearance: { ...SMOOTH_FINISH, material: 'pbr', metalness: 0.2, roughness: 0.5, specular: 0.2, outline: 0.15, outlineWidth: 0.6, transmode: 0 }, - }, -] - -/** Presets change shading only; layer data and periodic geometry retain their identities. */ -export const apply_surface_preset = (settings: IsosurfaceSettings, preset: SurfacePreset): IsosurfaceSettings => { - const definition = SURFACE_PRESETS.find((item) => item.value === preset) - return definition ? { ...settings, ...definition.appearance } : settings -} - -/** Match rendered effects, not click history. Diffuse and Goodsell resolve to Matte. */ -export const detect_surface_preset = (settings: SurfaceAppearance): SurfacePreset | 'custom' => { - const effective = { ...SURFACE_DEFAULTS, ...normalize_surface_appearance(settings) } - const definition = SURFACE_PRESETS.find(({ appearance }) => - (Object.keys(appearance) as Array).every((key) => { - if (effective.material === 'unlit' && key !== 'material' && key !== 'wireframe') return true - if ((key === 'roughness' || key === 'metalness') && effective.material !== 'pbr') return true - if ((key === 'shininess' || key === 'specular') && effective.material !== 'glossy') return true - if (key === 'outlineWidth' && effective.outline === 0) return true - const expected = appearance[key] - const actual = effective[key] - return typeof expected === 'number' && typeof actual === 'number' - ? Math.abs(expected - actual) < 1e-9 - : expected === actual - }), - ) - return definition?.value ?? 'custom' -} diff --git a/frontend/matterviz-viewer/src/periodic.ts b/frontend/matterviz-viewer/src/periodic.ts index 08d2fc93..19f342b5 100644 --- a/frontend/matterviz-viewer/src/periodic.ts +++ b/frontend/matterviz-viewer/src/periodic.ts @@ -1,6 +1,6 @@ import { EPS, - calc_lattice_params, + compute_lattice_params, create_cart_to_frac, det_3x3, type Matrix3x3, @@ -70,10 +70,10 @@ export const inject_manifest_lattice = ( if (!matrix) return structure let cart_to_frac: (cart: Vec3) => Vec3 - let lattice_params: ReturnType + let lattice_params: ReturnType try { cart_to_frac = create_cart_to_frac(matrix) - lattice_params = calc_lattice_params(matrix) + lattice_params = compute_lattice_params(matrix) } catch { return structure } diff --git a/frontend/matterviz-viewer/src/plot.ts b/frontend/matterviz-viewer/src/plot.ts index 0eff1676..c9383edf 100644 --- a/frontend/matterviz-viewer/src/plot.ts +++ b/frontend/matterviz-viewer/src/plot.ts @@ -112,13 +112,13 @@ export const parse_plot_artifact = (value: unknown): PlotArtifact => { return { format: 'multiwfn-matterviz-plot', version: 1, kind: item.kind as PlotKind, title: string_value(item.title, 'title'), panels: (item.panels as unknown[]).map(panel) } } -export type MatterVizSeries = { id: string; label?: string; x: number[]; y: number[]; markers: 'line' | 'line+points'; visible?: boolean; y_axis?: 'y1' | 'y2'; line_style?: { stroke?: string; stroke_width?: number; line_dash?: string }; point_style?: { radius: number; fill_opacity: number; stroke_opacity: number }; point_label?: Array<{ text?: string; auto_placement?: boolean }> } +export type MatterVizSeries = { id: string; label?: string; x: number[]; y: number[]; markers: 'line' | 'line+points'; visible?: boolean; y_axis?: 'y' | 'y2'; line_style?: { color?: string; width?: number; dash?: string }; point_style?: { radius: number; fill_opacity: number; stroke_opacity: number }; point_label?: Array<{ text?: string; auto_placement?: boolean }> } export const to_matterviz_series = (input: PlotSeries): MatterVizSeries => { const labels = input.labels?.map((label) => label ? { text: label, auto_placement: true } : {}) const label_style = labels ? { markers: 'line+points' as const, point_style: { radius: 0, fill_opacity: 0, stroke_opacity: 0 }, point_label: labels } : { markers: 'line' as const } - if (input.type === 'line') return { id: input.id, label: input.label, x: input.x, y: input.y, ...label_style, visible: input.visible, y_axis: input.axis === 'y2' ? 'y2' : 'y1', line_style: { stroke: input.color, stroke_width: input.lineWidth, line_dash: input.dash === 'dash' ? '6 4' : undefined } } + if (input.type === 'line') return { id: input.id, label: input.label, x: input.x, y: input.y, ...label_style, visible: input.visible, y_axis: input.axis === 'y2' ? 'y2' : 'y', line_style: { color: input.color, width: input.lineWidth, dash: input.dash === 'dash' ? '6 4' : undefined } } const first = input.x[0] - return { id: input.id, label: input.label, x: [first, first], y: [0, 0], markers: 'line', visible: input.visible, y_axis: input.axis === 'y2' ? 'y2' : 'y1', line_style: { stroke: input.color, stroke_width: input.lineWidth, line_dash: input.dash === 'dash' ? '6 4' : undefined } } + return { id: input.id, label: input.label, x: [first, first], y: [0, 0], markers: 'line', visible: input.visible, y_axis: input.axis === 'y2' ? 'y2' : 'y', line_style: { color: input.color, width: input.lineWidth, dash: input.dash === 'dash' ? '6 4' : undefined } } } export const stick_path = ( @@ -508,24 +508,24 @@ export const plot_render_values = (values: Float64Array): number[] => { return result } -export const to_matterviz_data_series = (layer: PlotSceneLayer, dataset: PlotDataset): { id: string; label?: string; x: number[]; y: number[]; markers: 'line' | 'points' | 'line+points'; x_axis: 'x1' | 'x2'; y_axis: 'y1' | 'y2'; visible?: boolean; line_style?: { stroke?: string; stroke_width?: number; line_dash?: string }; point_style?: { radius?: number; fill?: string; fill_opacity?: number; stroke?: string; stroke_opacity?: number } } => { +export const to_matterviz_data_series = (layer: PlotSceneLayer, dataset: PlotDataset): { id: string; label?: string; x: number[]; y: number[]; markers: 'line' | 'points' | 'line+points'; x_axis: 'x' | 'x2'; y_axis: 'y' | 'y2'; visible?: boolean; line_style?: { color?: string; width?: number; dash?: string }; point_style?: { radius?: number; fill?: string; fill_opacity?: number; stroke?: string; stroke_opacity?: number } } => { const points = materialize_plot_layer(layer, dataset) const style = layer.style ?? {} const markers = layer.type === 'line' ? 'line' : layer.type === 'scatter' ? 'points' : 'line+points' return { - id: layer.id, label: layer.label, x: plot_render_values(points.x), y: plot_render_values(points.y), markers, x_axis: layer.xAxis ?? 'x1', y_axis: layer.yAxis ?? 'y1', visible: layer.visible, - line_style: { stroke: typeof style.color === 'string' ? style.color : undefined, stroke_width: typeof style.width === 'number' ? style.width : undefined, line_dash: typeof style.dash === 'string' ? style.dash : undefined }, + id: layer.id, label: layer.label, x: plot_render_values(points.x), y: plot_render_values(points.y), markers, x_axis: layer.xAxis === 'x2' ? 'x2' : 'x', y_axis: layer.yAxis === 'y2' ? 'y2' : 'y', visible: layer.visible, + line_style: { color: typeof style.color === 'string' ? style.color : undefined, width: typeof style.width === 'number' ? style.width : undefined, dash: typeof style.dash === 'string' ? style.dash : undefined }, point_style: { radius: typeof style.markerSize === 'number' ? Math.max(1, style.markerSize / 10) : typeof style.radius === 'number' ? style.radius : undefined, fill: typeof style.color === 'string' ? style.color : undefined, fill_opacity: typeof style.opacity === 'number' ? style.opacity : undefined }, } } -export const to_matterviz_bar_series = (layer: PlotSceneLayer, dataset: PlotDataset): { id: string; label?: string; x: Float64Array; y: Float64Array; baseline: Float64Array; x_axis: 'x1' | 'x2'; y_axis: 'y1' | 'y2'; color?: string; visible?: boolean; bar_width?: number } => { +export const to_matterviz_bar_series = (layer: PlotSceneLayer, dataset: PlotDataset): { id: string; label?: string; x: Float64Array; y: Float64Array; baseline: Float64Array; x_axis: 'x' | 'x2'; y_axis: 'y' | 'y2'; color?: string; visible?: boolean; bar_width?: number } => { const points = materialize_plot_layer(layer, dataset) const baseline_raw = dataset.baseline if (!baseline_raw || baseline_raw.length !== points.y.length) scene_fail(`dataset ${layer.datasetId} is missing a matching baseline role for ${layer.id}`) const baseline = baseline_raw as Float64Array const style = layer.style ?? {} - return { id: layer.id, label: layer.label, x: points.x, y: points.y, baseline, x_axis: layer.xAxis ?? 'x1', y_axis: layer.yAxis ?? 'y1', color: typeof style.color === 'string' ? style.color : undefined, visible: layer.visible, bar_width: layer.width } + return { id: layer.id, label: layer.label, x: points.x, y: points.y, baseline, x_axis: layer.xAxis === 'x2' ? 'x2' : 'x', y_axis: layer.yAxis === 'y2' ? 'y2' : 'y', color: typeof style.color === 'string' ? style.color : undefined, visible: layer.visible, bar_width: layer.width } } export const to_matterviz_fill_region = (layer: PlotSceneLayer, dataset: PlotDataset): { id: string; label?: string; upper: { type: 'data'; values: number[]; x: number[] }; lower: { type: 'data'; values: number[]; x: number[] }; fill?: string; fill_opacity?: number; visible?: boolean } => { diff --git a/frontend/matterviz-viewer/src/rep-material.ts b/frontend/matterviz-viewer/src/rep-material.ts deleted file mode 100644 index c15a5d67..00000000 --- a/frontend/matterviz-viewer/src/rep-material.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { Material, Mesh, MeshBasicMaterial, Plane, type Object3D } from 'three' -import type { RepMaterial } from './reps.ts' - -const installed = new WeakMap() -const raycasts = new WeakSet() -const clipping = new WeakMap Plane[]>() - -/** Preserve the standard materials' rim/gradient hooks. Diffuse gain scales - * reflected light; saturation adjusts the tone-mapped linear RGB before output - * conversion and alpha compositing. Neither modifies source colors or data. */ -export const update_rep_material = (material: Material, appearance: RepMaterial, planes: Plane[]): void => { - let uniforms = installed.get(material) - if (!uniforms) { - uniforms = { diffuse: { value: appearance.diffuse }, saturation: { value: appearance.saturation } } - installed.set(material, uniforms) - const previous = material.onBeforeCompile, previousKey = material.customProgramCacheKey() - const { diffuse, saturation } = uniforms - material.onBeforeCompile = (shader, renderer) => { - previous.call(material, shader, renderer) - shader.uniforms.repDiffuse = diffuse - shader.uniforms.repSaturation = saturation - shader.fragmentShader = 'uniform float repDiffuse;\nuniform float repSaturation;\n' + shader.fragmentShader - shader.fragmentShader = shader.fragmentShader.replace('#include ', - '#include \nreflectedLight.directDiffuse *= repDiffuse;\nreflectedLight.indirectDiffuse *= repDiffuse;') - shader.fragmentShader = shader.fragmentShader.replace('#include ', `#include - if (repSaturation != 1.0) { - float repLuminance = dot(gl_FragColor.rgb, vec3(0.2126, 0.7152, 0.0722)); - gl_FragColor.rgb = max(vec3(0.0), mix(vec3(repLuminance), gl_FragColor.rgb, repSaturation)); - }`) - } - material.customProgramCacheKey = () => `${previousKey}:multiwfn-rep-v2` - material.needsUpdate = true - } - uniforms.diffuse.value = material instanceof MeshBasicMaterial ? 1 : appearance.diffuse - uniforms.saturation.value = appearance.saturation - if ((material.clippingPlanes?.length ?? 0) !== planes.length) material.needsUpdate = true - material.clippingPlanes = planes -} - -/** Clipped atoms/bonds must not remain invisible click targets. */ -export const clip_rep_raycast = (object: Object3D, planes: () => Plane[]): void => { - clipping.set(object, planes) - if (!(object instanceof Mesh) || raycasts.has(object)) return - raycasts.add(object) - const original = object.raycast - object.raycast = function (raycaster, intersections) { - const hits: typeof intersections = [] - original.call(this, raycaster, hits) - const active = clipping.get(object)?.() ?? [] - intersections.push(...hits.filter((hit) => active.every((plane) => plane.distanceToPoint(hit.point) >= -1e-6))) - } -} diff --git a/frontend/matterviz-viewer/src/rep-periodic.ts b/frontend/matterviz-viewer/src/rep-periodic.ts deleted file mode 100644 index f278fd7c..00000000 --- a/frontend/matterviz-viewer/src/rep-periodic.ts +++ /dev/null @@ -1,146 +0,0 @@ -import type { AnyStructure, Site, StructureBond } from 'matterviz/structure' -import { Box3, Matrix3, Plane, Vector3 } from 'three' -import { valid_cell, valid_range, type Cell, type Rep, type RepPeriodic, type Vec } from './reps.ts' - -export const MAX_REP_COPIES = 512 -export const MAX_REP_ATOMS = 100_000 -const EPSILON = 1e-8 -export const translate_cell = (cell: Cell, abc: Vec): Vec => [0, 1, 2].map((axis) => abc.reduce((sum, n, i) => sum + n * cell[i][axis], 0)) as Vec -const inverse = (cell: Cell): Matrix3 => new Matrix3().set( - cell[0][0], cell[1][0], cell[2][0], cell[0][1], cell[1][1], cell[2][1], cell[0][2], cell[1][2], cell[2][2], -).invert() - -export const fractional_position = (cell: Cell, position: Vec, origin: Vec = [0, 0, 0]): Vec => - new Vector3(...position).sub(new Vector3(...origin)).applyMatrix3(inverse(cell)).toArray() as Vec - -/** Six half spaces remain correct for skew and left-handed cells. */ -export const rep_clip_planes = (periodic: RepPeriodic, cell?: Cell, origin: Vec = [0, 0, 0]): Plane[] => { - if (!periodic.enabled) return [] - if (!valid_cell(cell)) throw new Error('Set valid lattice vectors before enabling periodic display') - if (!valid_range(periodic.range)) throw new Error('Each periodic lower bound must be below its upper bound') - const inv = inverse(cell).elements - return periodic.axes.flatMap((enabled, axis) => { - if (!enabled) return [] - const normal = new Vector3(inv[axis], inv[axis + 3], inv[axis + 6]) - const offset = normal.dot(new Vector3(...origin)) - return [new Plane(normal.clone(), -periodic.range[axis][0] - offset).normalize(), - new Plane(normal.clone().negate(), periodic.range[axis][1] + offset).normalize()] - }) -} - -export const rep_translations = (periodic: RepPeriodic, cell?: Cell): Vec[] => { - if (!periodic.enabled) return [[0, 0, 0]] - if (!valid_cell(cell) || !valid_range(periodic.range)) throw new Error('Invalid periodic cell or range') - const bounds = periodic.range.map(([lo, hi], axis) => periodic.axes[axis] ? [Math.floor(lo), Math.ceil(hi)] : [0, 1]) - const count = bounds.reduce((n, [lo, hi]) => n * (hi - lo), 1) - if (count > MAX_REP_COPIES) throw new Error(`Periodic display exceeds ${MAX_REP_COPIES} cells; reduce the range`) - const copies: Vec[] = [] - for (let a = bounds[0][0]; a < bounds[0][1]; a++) for (let b = bounds[1][0]; b < bounds[1][1]; b++) for (let c = bounds[2][0]; c < bounds[2][1]; c++) copies.push(translate_cell(cell, [a, b, c])) - return copies -} - -/** Small explicit selection language, with 1-based indices matching Multiwfn. */ -export const select_rep_sites = (structure: AnyStructure, expression: string): number[] => { - const text = expression.trim() - if (!text || text.toLowerCase() === 'all') return structure.sites.map((_, index) => index) - const element = /^element\s+([A-Za-z\s,]+)$/i.exec(text) - if (element) { - const elements = new Set(element[1].split(/[\s,]+/).filter(Boolean).map((item) => item.toLowerCase())) - return structure.sites.flatMap((site, index) => site.species.some((species) => elements.has(species.element.toLowerCase())) ? [index] : []) - } - const indices = /^index\s+([\d\s,\-]+)$/i.exec(text) - if (indices) { - const selected = new Set() - for (const token of indices[1].split(/[\s,]+/).filter(Boolean)) { - const match = /^(\d+)(?:-(\d+))?$/.exec(token) - if (!match) throw new Error('Use atom indices such as index 1-6, 9') - const first = Number(match[1]), last = Number(match[2] ?? match[1]) - if (first < 1 || last < first || last > structure.sites.length) throw new Error('Atom selection is outside the source structure') - for (let index = first; index <= last; index++) selected.add(index - 1) - } - return [...selected].sort((a, b) => a - b) - } - throw new Error('Use all, element C O, or index 1-6, 9') -} - -export type RepStructure = { structure: AnyStructure; sourceIndices: number[]; shifts: Vec[] } - -/** Expand positions, never mutate the source. The renderer computes finite bonds - * between these explicit atoms rather than adding a second implicit PBC layer. */ -export const rep_structure = (source: AnyStructure, rep: Rep, fallbackCell?: Cell): RepStructure => { - const indices = select_rep_sites(source, rep.structure.selection) - const cell = rep.periodic.cell ?? fallbackCell - const periodic = rep.periodic.enabled - if (periodic && (!valid_cell(cell) || !valid_range(rep.periodic.range))) throw new Error('Set valid lattice vectors and periodic ranges') - const sites: Site[] = [], sourceIndices: number[] = [], shifts: Vec[] = [] - const siteMap = new Map() - // Include centers just outside a cut so spheres and bonds end at the plane. - const inv = periodic ? inverse(cell!) : undefined - const margin = [0, 1, 2].map((axis) => inv && rep.periodic.boundary === 'clip' ? Math.hypot(inv.elements[axis], inv.elements[axis + 3], inv.elements[axis + 6]) * (3 * rep.structure.radius + 2) : 0) - for (const index of indices) { - const site = source.sites[index] - const frac = periodic ? fractional_position(cell!, site.xyz) : [0, 0, 0] - const bounds = rep.periodic.range.map(([lo, hi], axis) => periodic && rep.periodic.axes[axis] - ? [Math.ceil(lo - frac[axis] - margin[axis] - EPSILON), Math.floor(hi - frac[axis] + margin[axis] + (rep.periodic.boundary === 'none' ? -EPSILON : EPSILON))] : [0, 0]) - const count = bounds.reduce((n, [lo, hi]) => n * Math.max(0, hi - lo + 1), 1) - if (sites.length + count > MAX_REP_ATOMS) throw new Error(`Periodic display exceeds ${MAX_REP_ATOMS} atoms; reduce the range`) - for (let a = bounds[0][0]; a <= bounds[0][1]; a++) for (let b = bounds[1][0]; b <= bounds[1][1]; b++) for (let c = bounds[2][0]; c <= bounds[2][1]; c++) { - const shift: Vec = [a, b, c], translation = periodic ? translate_cell(cell!, shift) : [0, 0, 0] - const xyz = site.xyz.map((n, axis) => n + translation[axis]) as Vec - siteMap.set(`${index}:${shift.join(',')}`, sites.length) - sites.push({ ...site, xyz, abc: periodic ? fractional_position(cell!, xyz) : site.abc, - properties: { ...site.properties, orig_unit_cell_idx: index, rep_source_index: index, rep_cell_shift: shift } }) - sourceIndices.push(index); shifts.push(shift) - } - } - const bonds: StructureBond[] = [] - for (const [idx, original] of sourceIndices.entries()) { - for (const bond of source.properties?.bonds ?? []) { - if (bond.site_idx_1 !== original) continue - const targetShift = shifts[idx].map((n, axis) => n + (periodic ? bond.cell_shift?.[axis] ?? 0 : 0)) as Vec - const target = siteMap.get(`${bond.site_idx_2}:${targetShift.join(',')}`) - if (target !== undefined) bonds.push({ ...bond, site_idx_1: idx, site_idx_2: target, cell_shift: [0, 0, 0] }) - } - } - const structure = { ...source, sites, ...(source.properties?.bonds ? { properties: { ...source.properties, bonds } } : {}) } - // An explicit finite display is nonperiodic for bond detection. Its cell outline - // is drawn separately so it is never mistaken for the scientific source cell. - if ('lattice' in structure) structure.lattice = { ...structure.lattice, pbc: [false, false, false] } - return { structure, sourceIndices, shifts } -} - - -/** Bounds of the visible convex region, including intersections between skew cuts. */ -export const clipped_rep_bounds = (bounds: Box3, cuts: Plane[]): Box3 => { - if (bounds.isEmpty() || !cuts.length) return bounds.clone() - const planes = [...cuts, ...[0, 1, 2].flatMap((axis) => { - const normal = new Vector3().setComponent(axis, 1) - return [new Plane(normal, -bounds.min.getComponent(axis)), - new Plane(normal.clone().negate(), bounds.max.getComponent(axis))] - })] - const result = new Box3() - for (let a = 0; a < planes.length; a++) for (let b = a + 1; b < planes.length; b++) for (let c = b + 1; c < planes.length; c++) { - const [p, q, r] = [planes[a], planes[b], planes[c]] - const matrix = new Matrix3().set(...p.normal.toArray(), ...q.normal.toArray(), ...r.normal.toArray()) - if (Math.abs(matrix.determinant()) < 1e-10) continue - const point = new Vector3(-p.constant, -q.constant, -r.constant).applyMatrix3(matrix.invert()) - if (planes.every((plane) => plane.distanceToPoint(point) >= -1e-7)) result.expandByPoint(point) - } - return result -} - - -export type RepBondEdits = { added: StructureBond[]; removed: StructureBond[]; overrides: StructureBond[] } - -/** Native edit records use source indices. Expand each record into the same - * finite display as the atoms, including independently translated Reps. */ -export const rep_bonds = (display: RepStructure, bonds: StructureBond[], periodic: boolean): StructureBond[] => { - const lookup = new Map(display.sourceIndices.map((index, n) => [`${index}:${display.shifts[n].join(',')}`, n])) - const bySource = new Map() - for (const bond of bonds) bySource.set(bond.site_idx_1, [...(bySource.get(bond.site_idx_1) ?? []), bond]) - return display.sourceIndices.flatMap((sourceIndex, index) => (bySource.get(sourceIndex) ?? []).flatMap((bond) => { - const shift = display.shifts[index].map((n, axis) => n + (periodic ? bond.cell_shift?.[axis] ?? 0 : 0)) - const target = lookup.get(`${bond.site_idx_2}:${shift.join(',')}`) - return target === undefined ? [] : [{ ...bond, site_idx_1: index, site_idx_2: target, cell_shift: [0, 0, 0] as Vec }] - })) -} diff --git a/frontend/matterviz-viewer/src/representation.ts b/frontend/matterviz-viewer/src/representation.ts deleted file mode 100644 index 5482c604..00000000 --- a/frontend/matterviz-viewer/src/representation.ts +++ /dev/null @@ -1,185 +0,0 @@ -export type RepresentationPreset = 'ballstick' | 'spacefill' | 'stick' | 'wire' - -export type RepresentationSceneProps = Record - -export const REPRESENTATION_PRESETS: ReadonlyArray<{ - value: RepresentationPreset - label: string -}> = [ - { value: 'ballstick', label: 'Ball+Stick' }, - { value: 'spacefill', label: 'Spacefill' }, - { value: 'stick', label: 'Stick' }, - { value: 'wire', label: 'Wire' }, -] - -const ATOM_MIN = 0.1 -const ATOM_MAX = 3 -const BOND_MIN = 0.01 -const BOND_MAX = 1 -const DEFAULT_ATOM_RADIUS = 0.7 -const DEFAULT_BOND_THICKNESS = 0.07 -const ATOM_BASE_KEY = 'representation_atom_base' -const BOND_BASE_KEY = 'representation_bond_base' - -const finite_number = (value: unknown, fallback: number): number => { - if (typeof value === 'number' && Number.isFinite(value)) return value - if (typeof value === 'string' && value.trim() !== '') { - const parsed = Number(value) - if (Number.isFinite(parsed)) return parsed - } - return fallback -} - -const clamp = (value: number, minimum: number, maximum: number): number => - Math.min(maximum, Math.max(minimum, value)) - -const atom_radius = (value: unknown): number => - clamp(finite_number(value, DEFAULT_ATOM_RADIUS), ATOM_MIN, ATOM_MAX) - -const bond_thickness = (value: unknown): number => - clamp(finite_number(value, DEFAULT_BOND_THICKNESS), BOND_MIN, BOND_MAX) - -const preset_value = (value: unknown): RepresentationPreset | undefined => - value === 'ballstick' || value === 'spacefill' || value === 'stick' || value === 'wire' - ? value - : undefined - -const marker_matches_visibility = ( - scene_props: RepresentationSceneProps, - preset: RepresentationPreset, -): boolean => { - const expected_atoms = preset === 'ballstick' || preset === 'spacefill' - const expected_bonds = preset === 'spacefill' ? 'never' : 'always' - return (scene_props.show_atoms === undefined || scene_props.show_atoms === expected_atoms) - && (scene_props.show_bonds === undefined || scene_props.show_bonds === expected_bonds) -} - -export const normalize_representation_preset = (value: unknown): RepresentationPreset => - preset_value(value) ?? 'ballstick' - -/** - * Detect a preset from authoritative scene props. The explicit marker is set by - * apply_representation_preset and keeps manual refinement controls unambiguous; - * the structural fallback also handles restored or externally supplied props. - */ -export const detect_representation_preset = (scene_props: RepresentationSceneProps): RepresentationPreset => { - const marked = preset_value(scene_props.representation_preset) - if (marked && marker_matches_visibility(scene_props, marked)) return marked - - const show_atoms = scene_props.show_atoms !== false - const show_bonds = scene_props.show_bonds - if (show_atoms && show_bonds === 'never') return 'spacefill' - if (!show_atoms && (show_bonds === undefined || show_bonds === 'always')) { - // Wire is the only mode with a deliberately sub-bond-radius thickness at - // the standard base. Keep this heuristic conservative for legacy props. - return bond_thickness(scene_props.bond_thickness) <= 0.05 ? 'wire' : 'stick' - } - return 'ballstick' -} - -const base_values = (scene_props: RepresentationSceneProps): { - atom: number - bond: number -} => { - const current_preset = detect_representation_preset(scene_props) - const current_atom = atom_radius(scene_props.atom_radius) - const current_bond = bond_thickness(scene_props.bond_thickness) - - const marker = preset_value(scene_props.representation_preset) - const marker_is_current = marker !== undefined && marker === current_preset - && marker_matches_visibility(scene_props, marker) - let atom = marker_is_current - ? clamp(finite_number(scene_props[ATOM_BASE_KEY], current_atom), ATOM_MIN, ATOM_MAX) - : current_atom - let bond = marker_is_current - ? clamp(finite_number(scene_props[BOND_BASE_KEY], current_bond), BOND_MIN, BOND_MAX) - : current_bond - if (!marker_is_current && current_preset === 'spacefill') atom = current_atom / 1.85 - if (!marker_is_current && current_preset === 'stick') bond = current_bond / 1.18 - if (!marker_is_current && current_preset === 'wire') { - // The wire preset has a visible lower bound. At the bound, retain the - // user's refined value instead of manufacturing a larger base on every - // switch. - bond = current_bond <= 0.025 ? current_bond : current_bond / 0.28 - } - return { - atom: clamp(atom, ATOM_MIN, ATOM_MAX), - bond: clamp(bond, BOND_MIN, BOND_MAX), - } -} - -/** Map a named representation to one atomic scene-props update. */ -export const apply_representation_preset = ( - scene_props: RepresentationSceneProps, - preset: RepresentationPreset, -): RepresentationSceneProps => { - const normalized = normalize_representation_preset(preset) - const base = base_values(scene_props) - const atom = normalized === 'spacefill' - ? clamp(base.atom * 1.85, ATOM_MIN, ATOM_MAX) - : base.atom - const bond = normalized === 'stick' - ? clamp(base.bond * 1.18, BOND_MIN, BOND_MAX) - : normalized === 'wire' - ? clamp(Math.max(0.025, base.bond * 0.28), BOND_MIN, BOND_MAX) - : base.bond - - return { - ...scene_props, - representation_preset: normalized, - [ATOM_BASE_KEY]: base.atom, - [BOND_BASE_KEY]: base.bond, - show_atoms: normalized === 'ballstick' || normalized === 'spacefill', - show_bonds: normalized === 'spacefill' ? 'never' : 'always', - atom_radius: atom, - same_size_atoms: false, - bond_thickness: bond, - } -} - -const close_enough = (left: number, right: number): boolean => - Math.abs(left - right) <= 1e-9 - -/** Refine one displayed dimension while retaining its untransformed base. */ -export const refine_representation = ( - scene_props: RepresentationSceneProps, - key: 'atom_radius' | 'bond_thickness', - value: unknown, -): RepresentationSceneProps => { - const preset = detect_representation_preset(scene_props) - const next_value = key === 'atom_radius' - ? atom_radius(value) - : bond_thickness(value) - const base = base_values(scene_props) - const marker = preset_value(scene_props.representation_preset) - const marker_is_current = marker !== undefined && marker === preset - && marker_matches_visibility(scene_props, marker) - const marked_base = key === 'atom_radius' - ? clamp(finite_number(scene_props[ATOM_BASE_KEY], base.atom), ATOM_MIN, ATOM_MAX) - : clamp(finite_number(scene_props[BOND_BASE_KEY], base.bond), BOND_MIN, BOND_MAX) - const ratio = key === 'atom_radius' && preset === 'spacefill' - ? 1.85 - : key === 'bond_thickness' && preset === 'stick' - ? 1.18 - : key === 'bond_thickness' && preset === 'wire' - ? 0.28 - : 1 - const projected = key === 'atom_radius' - ? clamp(marked_base * ratio, ATOM_MIN, ATOM_MAX) - : clamp(preset === 'wire' ? Math.max(0.025, marked_base * ratio) : marked_base * ratio, BOND_MIN, BOND_MAX) - const next_base = marker_is_current && close_enough(projected, next_value) - ? marked_base - : key === 'bond_thickness' && preset === 'wire' && next_value <= 0.025 - ? next_value - : clamp(next_value / ratio, key === 'atom_radius' ? ATOM_MIN : BOND_MIN, key === 'atom_radius' ? ATOM_MAX : BOND_MAX) - return { - ...scene_props, - [key]: next_value, - ...(marker_is_current - ? { [key === 'atom_radius' ? ATOM_BASE_KEY : BOND_BASE_KEY]: next_base } - : {}), - } -} - -export const scene_props_for_representation = apply_representation_preset -export const representation_from_scene_props = detect_representation_preset diff --git a/frontend/matterviz-viewer/src/reps.css b/frontend/matterviz-viewer/src/reps.css deleted file mode 100644 index 971f2488..00000000 --- a/frontend/matterviz-viewer/src/reps.css +++ /dev/null @@ -1,92 +0,0 @@ -.rep-inspector { display: flex; flex-direction: column; min-height: 0; min-width: 0; overflow: hidden; background: #fcfdfe; border-right: 1px solid #dbe3eb; font-size: 12px; color: #233044; } -.rep-header { display: flex; align-items: center; justify-content: space-between; padding: 18px 16px 12px; } -.rep-header > div { display: grid; gap: 4px; } -.rep-header strong { font-size: 16px; letter-spacing: -.025em; } -.rep-header span { color: #768599; font-size: 11px; } -.rep-mode { display: flex; padding: 0 14px 12px; gap: 3px; } -.rep-mode button { flex: 1; display: flex; align-items: center; justify-content: center; gap: 6px; min-height: 33px; border: none; border-radius: 6px; background: #eef2f6; color: #68768a; font-size: 11px; } -.rep-mode button.chosen { background: #e0eef2; color: #14667e; font-weight: 650; } -.rep-list { flex-shrink: 0; max-height: 215px; overflow: auto; padding: 0 10px 8px; scrollbar-width: thin; } -.rep-row { display: flex; align-items: center; gap: 2px; margin: 3px 0; border: 1px solid transparent; border-radius: 7px; min-width: 0; } -.rep-row.selected { background: #eaf3f7; border-color: #c3dce6; } -.rep-row:hover { background: #f0f5f8; } -.rep-select { display: flex; align-items: center; width: 100%; gap: 8px; background: transparent; padding: 9px 9px 9px 0; border: 0; height: auto; text-align: left; color: inherit; overflow: hidden; } -.rep-select > svg { color: #7c91a4; flex-shrink: 0; } -.rep-number { font-size: 10px; font-variant-numeric: tabular-nums; color: #8a9aab; } -.rep-row-copy { display: grid; flex: 1; min-width: 0; gap: 3px; } -.rep-row-copy strong { font-weight: 600; font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } -.rep-row-copy small { font-size: 10px; color: #718198; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } -.rep-row.muted .rep-row-copy { opacity: .5; } -.rep-icon { display: inline-grid; place-items: center; flex-shrink: 0; width: 28px; height: 29px; border: 0; border-radius: 5px; padding: 0; color: #66798c; background: transparent; } -.rep-icon:hover:not(:disabled) { background: #e4edf3; color: #155e76; } -.rep-icon:disabled { opacity: .3; } -.rep-delete:hover:not(:disabled) { color: #ad3045; background: #ffedf0; } -.rep-actions { display: flex; align-items: center; gap: 4px; padding: 8px 14px 12px; border-bottom: 1px solid #e1e8ee; } -.rep-add { display: flex; align-items: center; justify-content: center; gap: 5px; flex: 1; min-height: 30px; font-size: 11px; font-weight: 600; border: 1px solid #cadbe5; border-radius: 6px; background: white; color: #176c86; } -.rep-name { display: grid; gap: 5px; padding: 14px 16px 10px; font-size: 10px; color: #758498; } -.rep-name input { font-weight: 600; } -.rep-tabs { display: flex; flex-direction: column; flex: 1; min-height: 0; } -.rep-tab-bar { display: flex; flex-shrink: 0; margin: 0 12px; padding: 3px; gap: 2px; height: 34px; background: #edf2f6; border-radius: 6px; } -.rep-tab-bar button { flex: 1; min-width: 0; height: 28px; gap: 4px; font-size: 10px; } -.rep-editor { flex: 1; min-height: 0; overflow: auto; padding: 16px; scrollbar-width: thin; } -.rep-tab-content { display: flex; flex-direction: column; gap: 13px; outline: none; } -.rep-section-label { display: flex; align-items: center; gap: 8px; font-size: 10px; font-weight: 650; color: #637990; letter-spacing: .025em; margin: 4px 0 0; } -.rep-section-label:not(:first-child) { margin-top: 8px; border-top: 1px solid #e4ebf1; padding-top: 19px; } -.rep-section-label > span { color: #98aabb; font-variant-numeric: tabular-nums; } -.rep-field { display: grid; gap: 6px; min-width: 0; } -.rep-field > span, .rep-scalar > span { color: #50647b; font-size: 11px; } -.rep-inspector :is(input:not([type='checkbox']):not([type='range']), select) { box-sizing: border-box; width: 100%; min-width: 0; height: 32px; background: #fff; border: 1px solid #d4dfe8; border-radius: 5px; color: #263c52; padding: 5px 8px; font: inherit; } -.rep-inspector input[type='color'] { padding: 3px; } -.rep-inspector :is(input, select, button):focus-visible { outline: 2px solid #2b89a4; outline-offset: 2px; } -.rep-fields { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; } -.rep-toggle { display: flex; align-items: center; gap: 8px; font-size: 11px; line-height: 1.5; color: #52687c; } -.rep-toggle input, .rep-axis input { width: 14px; height: 14px; margin: 0; accent-color: #176c86; } -.rep-style-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 7px; } -.rep-style-grid button { background: white; border: 1px solid #d9e3eb; padding: 8px 4px; font-size: 11px; border-radius: 6px; } -.rep-style-grid button.chosen { color: #176c86; background: #edf6f8; border-color: #a8cdd9; } -.rep-help { font-size: 10px; line-height: 1.65; margin: 0; color: #788a9d; } -.rep-scalar { display: grid; grid-template-columns: 1fr 64px; gap: 4px 8px; align-items: center; } -.rep-scalar > input[type='range'] { grid-column: 1 / -1; width: 100%; margin: 3px 0 0; height: 18px; accent-color: #297a91; } -.rep-details { border-top: 1px solid #e2eaf0; margin-top: 5px; padding-top: 14px; } -.rep-details summary { color: #5b7289; font-size: 11px; cursor: pointer; } -.rep-details[open] > :not(summary) { margin-top: 13px; } -.rep-periodic { display: grid; gap: 14px; } -.rep-range-grid { display: grid; grid-template-columns: 52px 1fr 1fr; gap: 8px; align-items: center; } -.rep-range-grid > span, .rep-cell-grid > span { color: #8293a5; font-size: 10px; } -.rep-axis { display: flex; align-items: center; gap: 8px; } -.rep-cell-grid { display: grid; grid-template-columns: 14px repeat(3, minmax(0, 1fr)); gap: 6px; align-items: center; } -.rep-inspector .rep-cell-grid input { padding: 4px; font-size: 11px; } -.rep-subheading { display: flex; justify-content: space-between; align-items: center; border-top: 1px solid #e1e8ef; padding-top: 15px; } -.rep-subheading strong { font-size: 11px; font-weight: 600; color: #5f768d; } -.rep-subheading span { color: #98a6b5; font-size: 10px; } -.rep-primary { min-height: 34px; background: #176c86; color: white; font-size: 11px; font-weight: 600; border: 0; border-radius: 6px; } -.rep-error { color: #a13748; background: #fff0f2; border-radius: 5px; padding: 8px; font-size: 11px; line-height: 1.5; } -.rep-empty { color: #8293a5; padding: 18px 12px; font-size: 11px; line-height: 1.6; text-align: center; } -.workspace { grid-template-columns: 44px 330px minmax(0, 1fr); } -.workspace.has-orbitals { grid-template-columns: 44px 330px minmax(0, 1fr) 250px; } -.rep-scene { display: flex; flex-direction: column; gap: 16px; } -.rep-scene h3 { color: #4f697e; font-size: 11px; margin: 4px 0 0; } -.rep-measure-tools { display: flex; align-items: center; gap: 8px; padding: 7px 12px; border-top: 1px solid #e3eaf0; background: #fbfcfd; font-size: 11px; color: #778b9d; } -.rep-measure-tools select { height: 27px; border: 1px solid #d6e2e9; border-radius: 4px; font-size: 11px; background: white; } -.rep-edit-banner { padding: 9px 14px; font-size: 12px; color: #536d81; background: #edf5f8; display: flex; align-items: center; gap: 10px; } -.viewer-shell:has(.rep-edit-banner) { grid-template-rows: auto minmax(0, 1fr) auto; } -@media (max-width: 1000px) and (min-width: 801px) { .workspace.has-orbitals { grid-template-columns: 40px 300px minmax(0, 1fr) 210px; } } -@media (max-width: 800px) { - .workspace, .workspace.has-orbitals { grid-template-columns: 40px minmax(0, 1fr); grid-template-rows: minmax(0, 55%) minmax(0, 1fr); } - .workspace > .rep-inspector { grid-column: 2; grid-row: 1; border-bottom: 1px solid #dce5ed; } - .workspace > .viewer-shell { grid-column: 2; grid-row: 2; } - .workspace > .tool-rail { grid-row: 1 / 3; } - .workspace.inspector-closed { grid-template-rows: minmax(0, 1fr); } - .workspace.inspector-closed > .viewer-shell { grid-row: 1; } - .rep-header { padding: 10px 12px 6px; } - .rep-header > div { display: flex; align-items: center; gap: 10px; } - .rep-header strong { font-size: 13px; } - .rep-mode { padding: 0 12px 6px; } - .rep-list { max-height: 64px; } - .rep-actions { padding: 4px 12px 6px; } - .rep-name { padding: 6px 12px; grid-template-columns: auto 1fr; align-items: center; gap: 10px; } - .rep-editor { padding: 10px 14px; } -} - -.rep-tab-content[hidden], .rep-tab-content[data-state='inactive'] { display: none !important; } -.rep-tab-bar [data-slot='tabs-trigger'] { font-size: 11px !important; padding: 3px 5px !important; gap: 4px !important; } diff --git a/frontend/matterviz-viewer/src/reps.ts b/frontend/matterviz-viewer/src/reps.ts deleted file mode 100644 index d737fc67..00000000 --- a/frontend/matterviz-viewer/src/reps.ts +++ /dev/null @@ -1,213 +0,0 @@ -import type { IsosurfaceLayer, IsosurfaceSettings } from 'matterviz' -import { SURFACE_DEFAULTS, SURFACE_PRESETS } from './material.ts' -import { detect_representation_preset, type RepresentationPreset } from './representation.ts' -import { migrate_color_scale, normalize_color_scale, preset_color_scale, type ColorScale } from './color-scale.ts' - -export type Vec = [number, number, number] -export type Cell = [Vec, Vec, Vec] -export type RepRange = [[number, number], [number, number], [number, number]] -export type RepMaterial = { - model: 'matte' | 'glossy' | 'pbr' | 'unlit' - opacity: number - diffuse: number - saturation: number - specular: number - shininess: number - roughness: number - metalness: number - outline: number - outlineWidth: number - angleOpacity: boolean - faceted: boolean -} -export type RepPeriodic = { - enabled: boolean - axes: [boolean, boolean, boolean] - range: RepRange - cell?: Cell - showCell: boolean - boundary: 'clip' | 'atoms' | 'none' -} -export type Rep = { - id: string - name: string - visible: boolean - followData?: boolean - source: { kind: 'structure' } | { kind: 'volume'; index: number; path?: string; slot?: number } - structure: { style: RepresentationPreset; selection: string; radius: number; bondRadius: number; labels: boolean; indices: boolean } - volume: IsosurfaceLayer & { wireframe: boolean; colorSourcePath?: string; colorSourceSlot?: number; colorScale?: ColorScale } - material: RepMaterial - periodic: RepPeriodic -} -export type RepCollection = { items: Rep[]; selectedId: string } -export const MAX_REPS = 32 -export const dataset_source = (entries: Array<{ path: string; datasetSlot?: number }>, index: number): Extract => ({ - kind: 'volume', index, path: entries[index]?.path, - slot: entries[index]?.datasetSlot ?? entries.slice(0, index).filter((entry) => entry.path === entries[index]?.path).length, -}) -export const dataset_key = (entries: Array<{ path: string; datasetSlot?: number }>, index: number): string => { - const source = dataset_source(entries, index) - return JSON.stringify([source.path ?? `index:${index}`, source.slot]) -} -export const DEFAULT_REP_MATERIAL: RepMaterial = { - model: 'glossy', opacity: 1, diffuse: 1, saturation: 1, specular: 0.28, shininess: 42, - roughness: 0.5, metalness: 0, outline: 0, outlineWidth: 0.6, - angleOpacity: false, faceted: false, -} -export const unit_range = (): RepRange => [[0, 1], [0, 1], [0, 1]] -export const create_rep = (source: Rep['source'], id: string = crypto.randomUUID()): Rep => ({ - id, name: source.kind === 'structure' ? 'Structure' : `Volume ${source.index + 1}`, visible: true, source: { ...source }, - structure: { style: 'ballstick', selection: 'all', radius: 0.7, bondRadius: 0.07, labels: false, indices: false }, - volume: { isovalue: 0.02, opacity: 1, color: '#3177ba', negative_color: '#ce5588', show_negative: true, visible: true, wireframe: false, volume_idx: source.kind === 'volume' ? source.index : 0, colorScale: preset_color_scale('interpolateTransFlag') }, - material: { ...DEFAULT_REP_MATERIAL }, - periodic: { enabled: false, axes: [true, true, true], range: unit_range(), showCell: false, boundary: 'clip' }, -}) - -export const copy_rep = (rep: Rep, id: string = crypto.randomUUID()): Rep => ({ ...structuredClone(rep), id, followData: false, name: `${rep.name} · 2` }) -const number = (value: unknown, fallback: number, lo: number, hi: number): number => - typeof value === 'number' && Number.isFinite(value) ? Math.min(hi, Math.max(lo, value)) : fallback -const record = (value: unknown): Record => value && typeof value === 'object' && !Array.isArray(value) ? value as Record : {} -const bool = (value: unknown, fallback: boolean): boolean => typeof value === 'boolean' ? value : fallback -const color = (value: unknown, fallback: string): string => typeof value === 'string' && /^#[0-9a-f]{6}$/i.test(value) ? value : fallback - -export const valid_cell = (value: unknown): value is Cell => { - if (!Array.isArray(value) || value.length !== 3 || !value.every((v) => Array.isArray(v) && v.length === 3 && v.every((n) => typeof n === 'number' && Number.isFinite(n)))) return false - const [a, b, c] = value as Cell - const determinant = a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0]) - const scale = Math.hypot(...a) * Math.hypot(...b) * Math.hypot(...c) - return scale > 1e-12 && Math.abs(determinant) > scale * 1e-8 -} -export const valid_range = (value: unknown): value is RepRange => - Array.isArray(value) && value.length === 3 && value.every((pair) => Array.isArray(pair) && pair.length === 2 && pair.every((n) => typeof n === 'number' && Number.isFinite(n) && Math.abs(n) <= 20) && pair[0] < pair[1]) - -export const normalize_rep = (value: unknown): Rep | undefined => { - const row = record(value), source = record(row.source) - if (typeof row.id !== 'string' || !row.id || (source.kind !== 'structure' && source.kind !== 'volume')) return - if (source.kind === 'volume' && (!Number.isInteger(source.index) || ((source.index as number) < 0 && !(source.index === -1 && typeof source.path === 'string')))) return - const rep = create_rep(source.kind === 'structure' ? { kind: 'structure' } : { kind: 'volume', index: source.index as number, ...(typeof source.path === 'string' ? { path: source.path } : {}), slot: Math.floor(number(source.slot, 0, 0, 100000)) }, row.id) - if (typeof row.name === 'string') rep.name = row.name.slice(0, 120) - rep.visible = bool(row.visible, true) - rep.followData = bool(row.followData, false) - const structure = record(row.structure), material = record(row.material), periodic = record(row.periodic), volume = record(row.volume) - if (['ballstick', 'spacefill', 'stick', 'wire'].includes(String(structure.style))) rep.structure.style = structure.style as RepresentationPreset - if (typeof structure.selection === 'string') rep.structure.selection = structure.selection.slice(0, 2000) - rep.structure.radius = number(structure.radius, 0.7, 0.1, 3) - rep.structure.bondRadius = number(structure.bondRadius, 0.07, 0.01, 1) - rep.structure.labels = bool(structure.labels, false); rep.structure.indices = bool(structure.indices, false) - if (['matte', 'glossy', 'pbr', 'unlit'].includes(String(material.model))) rep.material.model = material.model as RepMaterial['model'] - for (const key of ['opacity', 'specular', 'roughness', 'metalness', 'outline', 'outlineWidth'] as const) rep.material[key] = number(material[key], rep.material[key], 0, 1) - for (const key of ['diffuse', 'saturation'] as const) rep.material[key] = number(material[key], 1, 0, 3) - rep.material.shininess = number(material.shininess, 42, 1, 120) - rep.material.angleOpacity = bool(material.angleOpacity, false); rep.material.faceted = bool(material.faceted, false) - if (['clip', 'atoms', 'none'].includes(String(periodic.boundary))) rep.periodic.boundary = periodic.boundary as RepPeriodic['boundary'] - rep.periodic.enabled = bool(periodic.enabled, false); rep.periodic.showCell = bool(periodic.showCell, false) - if (Array.isArray(periodic.axes) && periodic.axes.length === 3 && periodic.axes.every((v) => typeof v === 'boolean')) rep.periodic.axes = [...periodic.axes] as RepPeriodic['axes'] - // Do not silently render a different cell/range when restoring malformed input. - if (periodic.cell !== undefined && !valid_cell(periodic.cell)) throw new Error('Invalid Rep lattice: vectors must form a nonsingular cell') - if (periodic.range !== undefined && !valid_range(periodic.range)) throw new Error('Invalid Rep range: each lower bound must be below its upper bound, within −20…20') - if (periodic.cell) rep.periodic.cell = (periodic.cell as Cell).map((vector) => [...vector]) as Cell - if (periodic.range) rep.periodic.range = (periodic.range as RepRange).map((pair) => [...pair]) as RepRange - rep.volume.isovalue = number(volume.isovalue, 0.02, -1e10, 1e10) - rep.volume.color = color(volume.color, rep.volume.color); rep.volume.negative_color = color(volume.negative_color, rep.volume.negative_color) - rep.volume.opacity = rep.material.opacity - rep.volume.show_negative = bool(volume.show_negative, true); rep.volume.wireframe = bool(volume.wireframe, false) - if (typeof volume.colormap === 'string' && /^interpolate[A-Za-z]+$/.test(volume.colormap)) rep.volume.colormap = volume.colormap as IsosurfaceLayer['colormap'] - if (Number.isInteger(volume.color_volume_idx) && (volume.color_volume_idx as number) >= 0) rep.volume.color_volume_idx = volume.color_volume_idx as number - if (typeof volume.colorSourcePath === 'string') rep.volume.colorSourcePath = volume.colorSourcePath - if (typeof volume.colorSourceSlot === 'number') rep.volume.colorSourceSlot = Math.floor(number(volume.colorSourceSlot, 0, 0, 100000)) - if (Array.isArray(volume.color_range) && volume.color_range.length === 2 && volume.color_range.every((n) => typeof n === 'number' && Number.isFinite(n))) rep.volume.color_range = [...volume.color_range].sort((a, b) => a - b) as [number, number] - rep.volume.colorScale = volume.colorScale !== undefined ? normalize_color_scale(volume.colorScale) - : volume.color_stops !== undefined ? normalize_color_scale({ stops: volume.color_stops }) - : migrate_color_scale({ colormap: rep.volume.colormap, color_range: rep.volume.color_range }) - return rep -} - -export const normalize_reps = (value: unknown): RepCollection | undefined => { - const row = record(value) - if (value === undefined) return - if (!Array.isArray(row.items)) throw new Error('Invalid representations in saved scene') - if (row.items.length > MAX_REPS) throw new Error(`A scene supports at most ${MAX_REPS} representations`) - const items = row.items.map(normalize_rep) - if (items.some((rep) => !rep)) throw new Error('Invalid representation in saved scene') - const valid = items as Rep[] - if (new Set(valid.map((rep) => rep.id)).size !== valid.length) throw new Error('Duplicate representation identities in saved scene') - return { items: valid, selectedId: valid.some((rep) => rep.id === row.selectedId) ? row.selectedId as string : valid[0]?.id ?? '' } -} - -export const rep_surface_settings = (rep: Rep, budget?: number): IsosurfaceSettings => ({ - ...SURFACE_DEFAULTS, isovalue: rep.volume.isovalue, opacity: rep.material.opacity, - positive_color: rep.volume.color, negative_color: rep.volume.negative_color, - show_negative: rep.volume.show_negative, wireframe: rep.volume.wireframe, halo: 0, - material: rep.material.model, roughness: rep.material.roughness, metalness: rep.material.metalness, - shininess: rep.material.shininess, specular: rep.material.specular, outline: rep.material.outline, - outlineWidth: rep.material.outlineWidth, transmode: rep.material.angleOpacity ? 1 : 0, flat_shading: rep.material.faceted, - layers: [{ ...rep.volume, color_stops: migrate_color_scale(rep.volume)?.stops, - color_range: rep.volume.color_range ? [...rep.volume.color_range].sort((a, b) => a - b) as [number, number] : undefined, - volume_idx: rep.source.kind === 'volume' ? rep.source.index : 0, opacity: rep.material.opacity, visible: rep.visible }], - geometry_memory_budget_bytes: budget, -}) - -export const rep_scene_props = (rep: Rep): Record => ({ - show_atoms: rep.structure.style === 'ballstick' || rep.structure.style === 'spacefill', - show_bonds: rep.structure.style === 'spacefill' ? 'never' : 'always', - atom_radius: rep.structure.radius, bond_thickness: rep.structure.bondRadius, same_size_atoms: false, - atom_material: rep.material.model, atom_opacity: rep.material.opacity, atom_roughness: rep.material.roughness, - atom_metalness: rep.material.metalness, atom_shininess: rep.material.shininess, atom_specular: rep.material.specular, - atom_outline: rep.material.outline, atom_outline_width: rep.material.outlineWidth, - atom_transmode: rep.material.angleOpacity ? 1 : 0, - show_site_labels: rep.structure.labels, show_site_indices: rep.structure.indices, - outline_enabled: false, -}) - -export const material_preset = (material: RepMaterial, preset: string): RepMaterial => { - const definition = SURFACE_PRESETS.find((item) => item.value === preset) - if (!definition) return material - const appearance = { ...SURFACE_DEFAULTS, ...definition.appearance } - return { ...material, opacity: preset.includes('glass') ? 0.35 : 1, model: appearance.material ?? 'matte', diffuse: 1, saturation: 1, specular: appearance.specular, - shininess: appearance.shininess, roughness: appearance.roughness, metalness: appearance.metalness, - outline: appearance.outline, outlineWidth: appearance.outlineWidth, - angleOpacity: appearance.transmode === 1, faceted: appearance.flat_shading } -} - -/** Migration is explicit; subsequent edits are owned only by the selected Rep. */ -export const migrate_reps = (scene: Record, settings: IsosurfaceSettings, entries: Array<{ path: string; name?: string; datasetSlot?: number }>, periodic = false, legacy?: { atomSupercell?: string; showBoundaryAtoms?: boolean; showUnitCell?: boolean }): RepCollection => { - const structure = create_rep({ kind: 'structure' }, 'structure-1') - structure.visible = scene.show_atoms !== false || scene.show_bonds !== 'never' - structure.structure = { ...structure.structure, style: detect_representation_preset(scene), radius: Number(scene.atom_radius) || 0.7, bondRadius: Number(scene.bond_thickness) || 0.07, labels: scene.show_site_labels === true, indices: scene.show_site_indices === true } - structure.material = { ...structure.material, model: (scene.atom_material as RepMaterial['model']) ?? 'glossy', opacity: typeof scene.atom_opacity === 'number' ? scene.atom_opacity : 1, roughness: Number(scene.atom_roughness ?? 0.32), metalness: Number(scene.atom_metalness ?? 0), specular: Number(scene.atom_specular ?? 0.28), shininess: Number(scene.atom_shininess ?? 42), outline: Number(scene.atom_outline ?? 0), outlineWidth: Number(scene.atom_outline_width ?? 0.6) } - structure.periodic.enabled = periodic; structure.periodic.showCell = periodic && legacy?.showUnitCell !== false - if (periodic) { - const scaling = legacy?.atomSupercell?.split(/[x×]/).map(Number) - if (scaling?.length === 3 && scaling.every((n) => Number.isInteger(n) && n > 0 && n <= 20)) structure.periodic.range = scaling.map((n) => [0, n]) as RepRange - structure.periodic.boundary = legacy?.showBoundaryAtoms === false ? 'none' : 'atoms' - } - const volumes = (settings.layers ?? []).slice(0, MAX_REPS - 1).map((layer, index) => { - const volumeIdx = layer.volume_idx ?? index - const rep = create_rep(dataset_source(entries, volumeIdx), `volume-${index + 1}`) - rep.followData = true - rep.name = entries[volumeIdx]?.name ?? `Volume ${volumeIdx + 1}` - rep.volume = { ...layer, colorScale: migrate_color_scale(layer), wireframe: settings.wireframe, colorSourcePath: layer.color_volume_idx === undefined ? undefined : entries[layer.color_volume_idx]?.path, - colorSourceSlot: layer.color_volume_idx === undefined ? undefined : dataset_source(entries, layer.color_volume_idx).slot } - const appearance = { ...SURFACE_DEFAULTS, ...settings } - rep.material = { ...rep.material, model: appearance.material ?? 'matte', opacity: layer.opacity, - roughness: appearance.roughness!, metalness: appearance.metalness!, shininess: appearance.shininess!, specular: appearance.specular!, - outline: appearance.outline!, outlineWidth: appearance.outlineWidth!, angleOpacity: appearance.transmode === 1, faceted: appearance.flat_shading! } - rep.visible = layer.visible - rep.periodic.enabled = periodic - if (valid_range(settings.display_range)) rep.periodic.range = settings.display_range.map((pair) => [...pair]) as RepRange - return rep - }) - return { items: [structure, ...volumes], selectedId: structure.id } -} - -/** Resolve by saved path when available. A missing source never falls back to another dataset. */ -export const remap_rep_sources = (collection: RepCollection, entries: Array<{ path: string; datasetSlot?: number }>): RepCollection => ({ - ...collection, items: collection.items.map((rep) => { - if (rep.source.kind !== 'volume') return rep - const path = rep.source.path - const match = (path: string, slot = 0) => entries.findIndex((entry, index) => entry.path === path && dataset_source(entries, index).slot === slot) - const index = path ? match(path, rep.source.slot) : rep.source.index - const colorIndex = rep.volume.colorSourcePath ? match(rep.volume.colorSourcePath, rep.volume.colorSourceSlot) : rep.volume.color_volume_idx - return { ...rep, source: { ...rep.source, index }, volume: { ...rep.volume, volume_idx: index, color_volume_idx: colorIndex } } - }), -}) diff --git a/frontend/matterviz-viewer/src/scene-export.ts b/frontend/matterviz-viewer/src/scene-export.ts index 7290a191..06a95599 100644 --- a/frontend/matterviz-viewer/src/scene-export.ts +++ b/frontend/matterviz-viewer/src/scene-export.ts @@ -1,12 +1,12 @@ -import { canvas_to_png_blob, scene_registry } from 'matterviz' +import { canvas_to_png_blob, scene_registry } from 'matterviz/io' -/** MatterViz displays the background with CSS; its WebGL canvas is transparent. - * Composite a solid background only in the saved image, leaving the live scene, - * camera, and translucent Rep materials unchanged. Omit it to keep PNG alpha. */ export const scene_to_png_blob = async (canvas: HTMLCanvasElement, background?: string): Promise => { - const scene = scene_registry.get(canvas) - if (!scene) throw new Error('The 3D renderer is not ready for export') - const blob = await canvas_to_png_blob(canvas, 150, scene.scene, scene.camera) + if (!scene_registry.has(canvas)) throw new Error('The 3D renderer is not ready for export') + return with_png_background(await canvas_to_png_blob(canvas, 150), background) +} + +// The viewports use CSS backgrounds. Composite the selected color into opaque exports. +export const with_png_background = async (blob: Blob, background?: string): Promise => { if (background === undefined) return blob const image = await createImageBitmap(blob) diff --git a/frontend/matterviz-viewer/src/session-fields.ts b/frontend/matterviz-viewer/src/session-fields.ts new file mode 100644 index 00000000..4a6eb695 --- /dev/null +++ b/frontend/matterviz-viewer/src/session-fields.ts @@ -0,0 +1,114 @@ +import { BOHR_TO_ANGSTROM } from 'matterviz/constants' +import { ISO_COLORMAPS, parse_cube, parse_volumetric_file, type IsosurfaceLayer, type VolumetricData } from 'matterviz/isosurface' +import { get_d3_interpolator } from 'matterviz/colors' +import { add, create_cart_to_frac, scale, type Vec3 } from 'matterviz/math' +import { Color } from 'three' +import { estimate_esp_range, normalize_esp_volume } from './esp.ts' +import type { ManifestEntry } from './manifest.ts' +import { resolve_volume_entry_url } from './manifest.ts' +import { adapt_matterviz_volume, decode_matterviz_volume, read_matterviz_volume_response } from './volume.ts' + +export type SessionField = { entry: ManifestEntry; volume: VolumetricData } + +export function field_id(entry: ManifestEntry, slot = entry.datasetSlot ?? 0): string { + // Streamed orbitals share an endpoint, and a single Cube can carry several fields. + return JSON.stringify([entry.path, entry.orbitalIndex ?? null, slot]) +} + +export function parse_session_cube(text: string, periodic?: boolean) { + const result = parse_cube(text, { periodic }) + // The upstream parser uses the Cube origin as zero for atoms and samples. + // A separate Multiwfn XYZ and native fields use absolute Cartesian coordinates. + const header = text.split(/\r?\n/, 4) + const origin = scale(header[2].trim().split(/\s+/).slice(1, 4).map(Number) as Vec3, + Number(header[3].trim().split(/\s+/, 1)[0]) > 0 ? BOHR_TO_ANGSTROM : 1) + const to_fractional = create_cart_to_frac(result.structure.lattice.matrix) + for (const site of result.structure.sites) { + site.xyz = add(site.xyz, origin) + site.abc = to_fractional(site.xyz) + } + for (const field of result.volumes) field.origin = origin + return result +} + +export async function load_field(entry: ManifestEntry, base: URL, periodic?: boolean) { + const url = resolve_volume_entry_url(entry, base) + const response = await fetch(url, { cache: 'no-store' }) + if (!response.ok) throw new Error(`${url.pathname}: HTTP ${response.status}`) + if (entry.format === 'mwfn-volume-v1' || entry.format === 'mwfn-volume-v2') { + const frame = decode_matterviz_volume(await read_matterviz_volume_response(response)) + const volume = adapt_matterviz_volume(frame, field_id(entry)) + volume.label = entry.name ?? entry.role + return { fields: [{ entry, volume }] } + } + const text = await response.text() + const parsed = entry.format === 'cube' || /\.cube?$/i.test(url.pathname) + ? parse_session_cube(text, periodic) + : parse_volumetric_file(text, entry.path) + if (!parsed) throw new Error(`MatterViz could not parse ${entry.path}`) + const fields = parsed.volumes.map((volume, index) => { + const slot = (entry.datasetSlot ?? 0) + index + volume.id = field_id(entry, slot) + volume.source = entry.path + volume.label = parsed.volumes.length === 1 ? entry.name ?? volume.label : volume.label + return { entry: { ...entry, datasetSlot: slot }, volume: normalize_esp_volume(volume, entry) } + }) + return { structure: parsed.structure, fields } +} + +function same_grid(a: VolumetricData, b: VolumetricData) { + const near = (x: number, y: number) => Math.abs(x - y) <= 1e-6 * Math.max(1, Math.abs(x), Math.abs(y)) + return a.periodic === b.periodic && a.dims.every((n, i) => n === b.dims[i]) + && a.origin.every((x, i) => near(x, b.origin[i])) + && a.lattice.every((row, i) => row.every((x, j) => near(x, b.lattice[i][j]))) +} + +export function layer_for_field({ entry, volume }: SessionField, fields: SessionField[]): IsosurfaceLayer { + const signed = entry.mode === 'signed' || entry.role === 'orbital' + const layer: IsosurfaceLayer = { + volume_id: volume.id, isovalue: entry.isovalue ?? (signed ? 0.02 : 0.001), + color: signed ? '#2563eb' : '#9ca3af', negative_color: '#dc2626', + visible: entry.visible !== false, show_negative: signed, opacity: entry.opacity ?? 0.82, + } + const mapping = entry.colorMapping + if (!mapping && entry.analysisKind !== 'esp-density') return layer + const color = fields.find(field => mapping ? field.entry.path === mapping.path + : field.entry.analysisKind === 'esp-potential' && same_grid(volume, field.volume)) + if (!color && !mapping) return layer + if (!color || color.volume.id === volume.id || !same_grid(volume, color.volume)) { + throw new Error('The mapped surface needs a separate coloring dataset on the same grid') + } + layer.color_volume_id = color.volume.id + if (!mapping) { + const { min, max } = estimate_esp_range(volume, color.volume, layer.isovalue, { maxCells: 150000, maxSamples: 50000 }) + layer.color_scale = { scheme: 'interpolateRdBu', value_range: [min, max] } + return layer + } + const { range, stops } = mapping + if (!Array.isArray(range) || range.length !== 2 || !range.every(Number.isFinite) || range[0] >= range[1]) { + throw new Error('The mapped surface color range must have finite, increasing bounds') + } + if (!Array.isArray(stops) || stops.length < 2 || stops.some((stop, i) => + !Number.isFinite(stop.position) || stop.position < 0 || stop.position > 1 || + (i > 0 && stop.position <= stops[i - 1].position) || !/^#[0-9a-f]{6}$/i.test(stop.color))) { + throw new Error('The mapped surface needs ordered color stops between 0 and 1') + } + // The native selector accepts named palettes. Match the declared stops in linear RGB + // in both directions, without reversing the physical range or the sampled field. + const targets = stops.map(s => ({ at: s.position, color: new Color(s.color) })) + let best = Infinity + for (const scheme of ISO_COLORMAPS) { + const interpolate = get_d3_interpolator(scheme) + for (const reverse of [false, true]) { + let error = 0 + for (const { at, color } of targets) { + const actual = new Color(interpolate(reverse ? 1 - at : at)) + error += (actual.r - color.r) ** 2 + (actual.g - color.g) ** 2 + (actual.b - color.b) ** 2 + } + if (error >= best) continue + best = error + layer.color_scale = { value_range: range, scheme, palette_range: reverse ? [1, 0] : [0, 1] } + } + } + return layer +} diff --git a/frontend/matterviz-viewer/src/slice-runtime.ts b/frontend/matterviz-viewer/src/slice-runtime.ts deleted file mode 100644 index 1cba30d5..00000000 --- a/frontend/matterviz-viewer/src/slice-runtime.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { sample_hkl_slice, type VolumetricData } from 'matterviz' -import { sample_slice_with, type NormalizedSlice } from './slice' - -export const sample_slice = ( - volume: VolumetricData | undefined, - miller_indices: unknown, - distance: unknown, - resolution?: unknown, -): NormalizedSlice | null => sample_slice_with( - sample_hkl_slice, - volume, - miller_indices, - distance, - resolution, -) diff --git a/frontend/matterviz-viewer/src/slice.ts b/frontend/matterviz-viewer/src/slice.ts deleted file mode 100644 index 1d79efd0..00000000 --- a/frontend/matterviz-viewer/src/slice.ts +++ /dev/null @@ -1,190 +0,0 @@ -import type { SliceResult, VolumetricData } from 'matterviz/isosurface' -import type { Vec3 } from 'matterviz/math' - -export type SliceAxis = 'xy' | 'xz' | 'yz' -export type SliceRange = readonly [number, number] -export type NormalizedSlice = { - data: Float64Array - width: number - height: number - min: number - max: number -} -export const SLICE_COLORMAPS = ['Viridis', 'RdBu', 'Jet', 'Portland'] as const -export type SliceColormap = (typeof SLICE_COLORMAPS)[number] -export type SliceSampler = ( - volume: VolumetricData, - miller_indices: Vec3, - distance: number, - n_points?: number, -) => SliceResult | null - -export const AXIS_PRESETS: Readonly> = { - xy: [0, 0, 1], - xz: [0, 1, 0], - yz: [1, 0, 0], -} - -export const AXIS_LABELS: Readonly> = { - xy: 'XY (001)', - xz: 'XZ (010)', - yz: 'YZ (100)', -} - -const finite_number = (value: unknown): number | undefined => { - if (value === null || value === undefined) return undefined - if (typeof value === 'string' && value.trim() === '') return undefined - const number = typeof value === 'number' ? value : Number(value) - return Number.isFinite(number) ? number : undefined -} - -export const clamp01 = (value: unknown): number => { - const number = finite_number(value) - if (number === undefined) return 0.5 - return Math.min(1, Math.max(0, number)) -} - -export const axis_to_miller = (axis: SliceAxis): Vec3 => [...(AXIS_PRESETS[axis] ?? AXIS_PRESETS.xy)] as Vec3 - -export const normalize_miller_indices = (value: unknown): Vec3 => { - const source = Array.isArray(value) || ArrayBuffer.isView(value) ? Array.from(value as ArrayLike) : [] - return [0, 1, 2].map((index) => { - const number = finite_number(source[index]) - return number === undefined ? 0 : Math.round(number) - }) as Vec3 -} - -const integer_dimension = (value: unknown): number | undefined => { - const number = finite_number(value) - if (number === undefined || number < 1) return undefined - return Math.max(1, Math.floor(number)) -} - -export const normalize_slice_resolution = (value: unknown): number => { - const number = integer_dimension(value) ?? 128 - return Math.min(512, Math.max(2, number)) -} - -const finite_data_range = (values: ArrayLike): SliceRange => { - let min = Infinity - let max = -Infinity - for (let index = 0; index < values.length; index += 1) { - const value = finite_number(values[index]) - if (value === undefined) continue - min = Math.min(min, value) - max = Math.max(max, value) - } - return Number.isFinite(min) && Number.isFinite(max) ? [min, max] : [0, 1] -} - -/** Convert a MatterViz slice result into a safe, finite-dimension result. - * Missing cells are represented by NaN so they do not affect the data range. - */ -export const normalize_slice_result = (result: unknown): NormalizedSlice | null => { - if (!result || typeof result !== 'object') return null - const candidate = result as Partial & { data?: ArrayLike } - const width = integer_dimension(candidate.width) - const height = integer_dimension(candidate.height) - if (!width || !height || !candidate.data || typeof candidate.data.length !== 'number') return null - - const data = new Float64Array(width * height) - data.fill(Number.NaN) - const source = candidate.data - const copied = Math.min(data.length, source.length) - for (let index = 0; index < copied; index += 1) { - const value = finite_number(source[index]) - if (value !== undefined) data[index] = value - } - const [min, max] = finite_data_range(data) - return { data, width, height, min, max } -} - -export const sample_slice_with = ( - sampler: SliceSampler, - volume: VolumetricData | undefined, - miller_indices: unknown, - distance: unknown, - resolution: unknown = undefined, -): NormalizedSlice | null => { - if (!volume) return null - const miller = normalize_miller_indices(miller_indices) - if (miller.every((value) => value === 0)) return null - const points = resolution === undefined ? undefined : normalize_slice_resolution(resolution) - try { - return normalize_slice_result(sampler(volume, miller, clamp01(distance), points)) - } catch { - return null - } -} - -/** Resolve an automatic or manual color range. Non-finite bounds fall back to data. */ -export const resolve_slice_range = ( - values: ArrayLike | NormalizedSlice, - manual_min?: unknown, - manual_max?: unknown, -): SliceRange => { - const data = 'data' in values ? values.data : values - const [automatic_min, automatic_max] = finite_data_range(data) - const min = finite_number(manual_min) ?? automatic_min - const max = finite_number(manual_max) ?? automatic_max - return min <= max ? [min, max] : [max, min] -} - -export const normalize_scalar = (value: unknown, range: SliceRange): number => { - const number = finite_number(value) - if (number === undefined) return Number.NaN - const [minimum, maximum] = range - if (!Number.isFinite(minimum) || !Number.isFinite(maximum)) return 0.5 - if (minimum === maximum) return 0.5 - return Math.min(1, Math.max(0, (number - minimum) / (maximum - minimum))) -} - -const COLOR_STOPS: Record = { - Viridis: [[68, 1, 84], [59, 82, 139], [33, 145, 140], [94, 201, 98], [253, 231, 37]], - RdBu: [[5, 48, 97], [67, 147, 195], [247, 247, 247], [214, 96, 77], [103, 0, 31]], - Jet: [[0, 0, 128], [0, 128, 255], [128, 255, 128], [255, 128, 0], [128, 0, 0]], - Portland: [[12, 51, 131], [10, 136, 186], [242, 211, 56], [242, 143, 56], [217, 30, 30]], -} - -const interpolate_color = (value: number, colormap: SliceColormap): [number, number, number] => { - const stops = COLOR_STOPS[colormap] - const scaled = value * (stops.length - 1) - const lower = Math.min(stops.length - 1, Math.floor(scaled)) - const upper = Math.min(stops.length - 1, lower + 1) - const fraction = scaled - lower - return stops[lower].map((channel, index) => - Math.round(channel + (stops[upper][index] - channel) * fraction)) as [number, number, number] -} - -export const scalar_to_rgba = ( - value: unknown, - range: SliceRange, - colormap: SliceColormap | string = 'Viridis', -): [number, number, number, number] => { - const normalized = normalize_scalar(value, range) - if (!Number.isFinite(normalized)) return [0, 0, 0, 0] - const selected = SLICE_COLORMAPS.includes(colormap as SliceColormap) - ? colormap as SliceColormap - : 'Viridis' - const [red, green, blue] = interpolate_color(normalized, selected) - return [red, green, blue, 255] -} - -export const slice_to_rgba = ( - slice: NormalizedSlice | null, - range?: SliceRange, - colormap: SliceColormap | string = 'Viridis', -): Uint8ClampedArray => { - if (!slice) return new Uint8ClampedArray() - const resolved = range ?? resolve_slice_range(slice) - const rgba = new Uint8ClampedArray(slice.data.length * 4) - for (let index = 0; index < slice.data.length; index += 1) { - const color = scalar_to_rgba(slice.data[index], resolved, colormap) - rgba.set(color, index * 4) - } - return rgba -} - -// Descriptive aliases make the helpers convenient to consume from plain tests and hosts. -export const normalize_sample_result = normalize_slice_result -export const colorize_slice = slice_to_rgba diff --git a/frontend/matterviz-viewer/src/state.ts b/frontend/matterviz-viewer/src/state.ts deleted file mode 100644 index 0cd71991..00000000 --- a/frontend/matterviz-viewer/src/state.ts +++ /dev/null @@ -1,545 +0,0 @@ -import type { CameraProjection, IsosurfaceLayer, IsosurfaceSettings, Vec3 } from 'matterviz' -import type { ManifestEntry, MultiwfnManifest } from './manifest' -import type { SliceAxis, SliceColormap } from './slice' -import { normalize_topology_display, type TopologyDisplay } from './topology.ts' -import { normalize_surface_appearance } from './material.ts' -import { normalize_lighting } from './lighting.ts' -import { normalize_atom_style, type AtomStyleSettings } from './atom-style.ts' -import { normalize_reps, remap_rep_sources, type RepCollection } from './reps.ts' - -const WORKBENCH_SLICE_COLORMAPS = new Set(['Viridis', 'RdBu', 'Jet', 'Portland']) - -export type WorkbenchCameraState = { - position?: Vec3 - target?: Vec3 - up?: Vec3 - zoom?: number - projection?: CameraProjection -} - -export type WorkbenchIsosurfaceAppearance = { - wireframe?: boolean - material?: IsosurfaceSettings['material'] - roughness?: number - metalness?: number - shininess?: number - specular?: number - flatShading?: boolean - outline?: number - outlineWidth?: number - transmode?: number - halo?: number -} - -export type WorkbenchStructureAppearance = { - representationPreset?: 'ballstick' | 'spacefill' | 'stick' | 'wire' - representationAtomBase?: number - representationBondBase?: number - showAtoms?: boolean - showBonds?: 'always' | 'never' | 'crystals' | 'molecules' - showGizmo?: boolean - atomRadius?: number - sameSizeAtoms?: boolean - bondThickness?: number - bondingStrategy?: 'electroneg_ratio' | 'solid_angle' - showSiteLabels?: boolean - showSiteIndices?: boolean - sphereSegments?: number - ambientLight?: number - directionalLight?: number - fillLight?: number - rimLight?: number - lightingRig?: 'default' | 'tmim' - sceneToneMapping?: 'agx' | 'none' - atomStyle?: AtomStyleSettings['atom_style'] - atomMaterial?: 'matte' | 'glossy' | 'pbr' - atomRoughness?: number - atomMetalness?: number - atomOpacity?: number - atomOutline?: number - atomOutlineWidth?: number - backgroundColor?: string - backgroundOpacity?: number -} - -export type WorkbenchSliceState = { - open?: boolean - plane?: SliceAxis - millerIndices?: [number, number, number] - position?: number - resolution?: number - colormap?: SliceColormap - rangeMode?: 'auto' | 'manual' - manualMin?: number - manualMax?: number -} - -export type WorkbenchEspLegendState = { - visible?: boolean - position?: { left: number; top: number } -} - -export type MatterVizWorkbenchState = { - format: 'multiwfn-matterviz-workbench' - version: 1 - representations?: RepCollection - sourceManifest?: string - activeVolume: number - volumes: Array - periodic?: { - displayRange?: [[number, number], [number, number], [number, number]] - atomSupercell: string - showBoundaryAtoms: boolean - showUnitCell: boolean - } - camera?: WorkbenchCameraState - isosurface?: WorkbenchIsosurfaceAppearance - structureAppearance?: WorkbenchStructureAppearance - slice?: WorkbenchSliceState - espLegend?: WorkbenchEspLegendState - topologyDisplay?: TopologyDisplay - session: Pick -} - -export type WorkbenchStateInput = { - representations?: RepCollection - manifest: MultiwfnManifest - sourceManifest?: string - entries: ManifestEntry[] - isosurfaceSettings: IsosurfaceSettings - activeVolume: number - atomSupercell: string - showBoundaryAtoms: boolean - showUnitCell: boolean - camera?: WorkbenchCameraState - sceneProps?: Record - backgroundColor?: string - backgroundOpacity?: number - slice?: WorkbenchSliceState - espLegend?: WorkbenchEspLegendState - topologyDisplay?: TopologyDisplay -} - -export type WorkbenchStateRestoration = { - representations?: RepCollection - activeVolume: number - isosurfaceSettings: IsosurfaceSettings - periodic?: MatterVizWorkbenchState['periodic'] - camera?: WorkbenchCameraState - structureAppearance?: WorkbenchStructureAppearance - slice?: WorkbenchSliceState - espLegend?: WorkbenchEspLegendState - topologyDisplay?: TopologyDisplay -} - -const as_record = (value: unknown): Record => - value !== null && typeof value === 'object' && !Array.isArray(value) - ? value as Record - : {} - -const record_or_undefined = (value: unknown): Record | undefined => - value !== null && typeof value === 'object' && !Array.isArray(value) - ? value as Record - : undefined - -const finite_number = (value: unknown): number | undefined => { - if (typeof value === 'number') return Number.isFinite(value) ? value : undefined - if (typeof value === 'string' && value.trim() !== '') { - const parsed = Number(value) - return Number.isFinite(parsed) ? parsed : undefined - } - return undefined -} - -const finite_integer = (value: unknown): number | undefined => { - const number = finite_number(value) - return number === undefined ? undefined : Math.trunc(number) -} - -const clamp_finite = (value: unknown, minimum: number, maximum: number): number | undefined => { - const number = finite_number(value) - return number === undefined ? undefined : Math.min(maximum, Math.max(minimum, number)) -} - -const clamp_positive = (value: unknown, minimum: number, maximum: number): number | undefined => - clamp_finite(value, minimum, maximum) - -const normalize_structure_appearance = (value: unknown): WorkbenchStructureAppearance | undefined => { - const row = as_record(value) - const appearance: WorkbenchStructureAppearance = {} - const read = (camel: string, snake: string): unknown => row[camel] ?? row[snake] - - const representationPreset = read('representationPreset', 'representation_preset') - if (representationPreset === 'ballstick' || representationPreset === 'spacefill' - || representationPreset === 'stick' || representationPreset === 'wire') { - appearance.representationPreset = representationPreset - } - const representationAtomBase = clamp_positive(read('representationAtomBase', 'representation_atom_base'), 0.1, 3) - if (representationAtomBase !== undefined) appearance.representationAtomBase = representationAtomBase - const representationBondBase = clamp_positive(read('representationBondBase', 'representation_bond_base'), 0.01, 1) - if (representationBondBase !== undefined) appearance.representationBondBase = representationBondBase - - const showAtoms = read('showAtoms', 'show_atoms') - if (typeof showAtoms === 'boolean') appearance.showAtoms = showAtoms - const showBonds = read('showBonds', 'show_bonds') - if (showBonds === 'always' || showBonds === 'never' || showBonds === 'crystals' || showBonds === 'molecules') { - appearance.showBonds = showBonds - } - const showGizmo = read('showGizmo', 'show_gizmo') - if (typeof showGizmo === 'boolean') appearance.showGizmo = showGizmo - const atomRadius = clamp_positive(read('atomRadius', 'atom_radius'), 0.1, 3) - if (atomRadius !== undefined) appearance.atomRadius = atomRadius - const sameSizeAtoms = read('sameSizeAtoms', 'same_size_atoms') - if (typeof sameSizeAtoms === 'boolean') appearance.sameSizeAtoms = sameSizeAtoms - const bondThickness = clamp_positive(read('bondThickness', 'bond_thickness'), 0.01, 1) - if (bondThickness !== undefined) appearance.bondThickness = bondThickness - const bondingStrategy = read('bondingStrategy', 'bonding_strategy') - if (bondingStrategy === 'electroneg_ratio' || bondingStrategy === 'solid_angle') { - appearance.bondingStrategy = bondingStrategy - } - const showSiteLabels = read('showSiteLabels', 'show_site_labels') - if (typeof showSiteLabels === 'boolean') appearance.showSiteLabels = showSiteLabels - const showSiteIndices = read('showSiteIndices', 'show_site_indices') - if (typeof showSiteIndices === 'boolean') appearance.showSiteIndices = showSiteIndices - const sphereSegments = finite_integer(read('sphereSegments', 'sphere_segments')) - if (sphereSegments !== undefined) appearance.sphereSegments = Math.min(64, Math.max(8, sphereSegments)) - const lighting = normalize_lighting(row) - if (lighting.ambient_light !== undefined) appearance.ambientLight = lighting.ambient_light - if (lighting.directional_light !== undefined) appearance.directionalLight = lighting.directional_light - if (lighting.fill_light !== undefined) appearance.fillLight = lighting.fill_light - if (lighting.rim_light !== undefined) appearance.rimLight = lighting.rim_light - if (lighting.lighting_rig !== undefined) appearance.lightingRig = lighting.lighting_rig - if (lighting.scene_tone_mapping !== undefined) appearance.sceneToneMapping = lighting.scene_tone_mapping - const atom = normalize_atom_style(row) - if (atom.atom_style !== undefined) appearance.atomStyle = atom.atom_style - const atomMaterial = read('atomMaterial', 'atom_material') - if (atomMaterial === 'matte' || atomMaterial === 'glossy' || atomMaterial === 'pbr') appearance.atomMaterial = atomMaterial - if (atom.atom_roughness !== undefined) appearance.atomRoughness = atom.atom_roughness - if (atom.atom_metalness !== undefined) appearance.atomMetalness = atom.atom_metalness - if (atom.atom_opacity !== undefined) appearance.atomOpacity = atom.atom_opacity - if (atom.atom_outline !== undefined) appearance.atomOutline = atom.atom_outline - if (atom.atom_outline_width !== undefined) appearance.atomOutlineWidth = atom.atom_outline_width - const backgroundColor = normalize_color(read('backgroundColor', 'background_color')) - if (backgroundColor !== undefined) appearance.backgroundColor = backgroundColor - const backgroundOpacity = clamp_finite(read('backgroundOpacity', 'background_opacity'), 0, 1) - if (backgroundOpacity !== undefined) appearance.backgroundOpacity = backgroundOpacity - - return Object.keys(appearance).length ? appearance : undefined -} - -const finite_pair = (value: unknown): [number, number] | undefined => { - if (!Array.isArray(value) || value.length < 2) return undefined - const left = finite_number(value[0]) - const right = finite_number(value[1]) - return left !== undefined && right !== undefined ? [left, right] : undefined -} - -const finite_vec3 = (value: unknown): Vec3 | undefined => { - if (!Array.isArray(value) || value.length < 3) return undefined - const result = [finite_number(value[0]), finite_number(value[1]), finite_number(value[2])] - return result.every((item) => item !== undefined) ? result as Vec3 : undefined -} - -const normalize_camera = (value: unknown): WorkbenchCameraState | undefined => { - const row = as_record(value) - const position = finite_vec3(row.position) - const target = finite_vec3(row.target) - const up = finite_vec3(row.up) - const zoomValue = finite_number(row.zoom) - const zoom = zoomValue !== undefined && zoomValue > 0 ? zoomValue : undefined - const projection = row.projection === 'perspective' || row.projection === 'orthographic' - ? row.projection - : undefined - if (!position && !target && !up && zoom === undefined && !projection) return undefined - return { position, target, up, zoom, projection } -} - -const normalize_appearance = (value: unknown): WorkbenchIsosurfaceAppearance | undefined => { - const row = as_record(value) - const { flat_shading, ...appearance } = normalize_surface_appearance({ - ...row, - flat_shading: row.flatShading ?? row.flat_shading, - }) - const result: WorkbenchIsosurfaceAppearance = appearance - if (flat_shading !== undefined) result.flatShading = flat_shading - return Object.keys(result).length ? result : undefined -} - -const normalize_color = (value: unknown): string | undefined => - typeof value === 'string' && value.trim() !== '' ? value : undefined - -const normalize_slice = (value: unknown): WorkbenchSliceState | undefined => { - const row = as_record(value) - const slice: WorkbenchSliceState = {} - const open = row.open ?? row.visible - if (typeof open === 'boolean') slice.open = open - const plane = row.plane ?? row.axis - if (plane === 'xy' || plane === 'xz' || plane === 'yz') slice.plane = plane - const millerValue = row.millerIndices ?? row.miller_indices - if (Array.isArray(millerValue) && millerValue.length >= 3) { - const values = millerValue.slice(0, 3).map(finite_integer) - if (values.every((item) => item !== undefined)) slice.millerIndices = values as [number, number, number] - } - const position = clamp_finite(row.position, 0, 1) - if (position !== undefined) slice.position = position - const resolution = finite_integer(row.resolution) - if (resolution !== undefined) slice.resolution = Math.min(512, Math.max(2, resolution)) - const colormap = row.colormap - if (typeof colormap === 'string' && WORKBENCH_SLICE_COLORMAPS.has(colormap)) { - slice.colormap = colormap as SliceColormap - } - const rangeMode = row.rangeMode ?? row.range_mode - if (rangeMode === 'auto' || rangeMode === 'manual') slice.rangeMode = rangeMode - const manualMin = finite_number(row.manualMin ?? row.manual_min) - const manualMax = finite_number(row.manualMax ?? row.manual_max) - if (manualMin !== undefined) slice.manualMin = manualMin - if (manualMax !== undefined) slice.manualMax = manualMax - return Object.keys(slice).length ? slice : undefined -} - -const normalize_legend = (value: unknown): WorkbenchEspLegendState | undefined => { - const row = as_record(value) - const legend: WorkbenchEspLegendState = {} - const visible = row.visible ?? row.open - if (typeof visible === 'boolean') legend.visible = visible - const position = as_record(row.position) - const left = finite_number(position.left) - const top = finite_number(position.top) - if (left !== undefined && top !== undefined) legend.position = { left, top } - return Object.keys(legend).length ? legend : undefined -} - -const ISO_COLORMAPS = new Set([ - 'interpolateTransFlag', - 'interpolateViridis', 'interpolatePlasma', 'interpolateInferno', 'interpolateMagma', - 'interpolateCividis', 'interpolateTurbo', 'interpolateRdBu', 'interpolateRdYlBu', - 'interpolateSpectral', 'interpolatePiYG', 'interpolateBrBG', 'interpolatePuOr', - 'interpolateCool', 'interpolateWarm', 'interpolateRdYlGn', 'interpolateGreys', 'interpolateTransFlag', -]) - -const normalize_layer_snapshot = (value: unknown): MatterVizWorkbenchState['volumes'][number] | undefined => { - const row = as_record(value) - const path = typeof row.path === 'string' && row.path.trim() !== '' ? row.path : undefined - const volumeIndex = finite_integer(row.volumeIndex) - if (!path || volumeIndex === undefined || volumeIndex < 0) return undefined - const entry: MatterVizWorkbenchState['volumes'][number] = { path, volumeIndex } - for (const key of ['name', 'format', 'role', 'mode', 'analysisKind'] as const) { - if (typeof row[key] === 'string') entry[key] = row[key] - } - for (const key of ['isovalue', 'opacity', 'orbitalIndex', 'datasetSlot'] as const) { - const number = finite_number(row[key]) - if (number !== undefined) entry[key] = number - } - if (typeof row.visible === 'boolean') entry.visible = row.visible - const color = normalize_color(row.color) - const negativeColor = normalize_color(row.negativeColor) - if (color !== undefined) entry.color = color - if (negativeColor !== undefined) entry.negativeColor = negativeColor - if (typeof row.showNegative === 'boolean') entry.showNegative = row.showNegative - const colorVolumeIndex = finite_integer(row.colorVolumeIndex) - if (colorVolumeIndex !== undefined && colorVolumeIndex >= 0) entry.colorVolumeIndex = colorVolumeIndex - const colormap = normalize_color(row.colormap) - if (colormap !== undefined && ISO_COLORMAPS.has(colormap)) entry.colormap = colormap - const colorRange = finite_pair(row.colorRange) - if (colorRange) entry.colorRange = colorRange[0] <= colorRange[1] ? colorRange : [colorRange[1], colorRange[0]] - return entry -} - -export const create_workbench_state = (input: WorkbenchStateInput): MatterVizWorkbenchState => { - const layers = input.isosurfaceSettings.layers ?? [] - const layerByVolume = new Map(layers.map((layer) => [layer.volume_idx ?? 0, layer])) - const displayRange = input.isosurfaceSettings.display_range - ?.map(finite_pair) - const validDisplayRange = displayRange?.length === 3 && displayRange.every(Boolean) - ? displayRange as [[number, number], [number, number], [number, number]] - : undefined - const appearance = normalize_appearance(input.isosurfaceSettings) - const sceneProps = { ...(input.sceneProps ?? {}) } - const backgroundColor = normalize_color(input.backgroundColor) - if (backgroundColor !== undefined) sceneProps.backgroundColor = backgroundColor - const backgroundOpacity = clamp_finite(input.backgroundOpacity, 0, 1) - if (backgroundOpacity !== undefined) sceneProps.backgroundOpacity = backgroundOpacity - const structureAppearance = normalize_structure_appearance(sceneProps) - - return { - format: 'multiwfn-matterviz-workbench', - version: 1, - sourceManifest: input.sourceManifest, - representations: input.representations ? normalize_reps(input.representations) : undefined, - activeVolume: Math.min( - Math.max(0, input.entries.length - 1), - Math.max(0, Math.trunc(Number(input.activeVolume) || 0)), - ), - volumes: input.entries.map((entry, volumeIndex) => { - const layer = layerByVolume.get(volumeIndex) - const range = finite_pair(layer?.color_range) - return { - ...entry, - volumeIndex, - isovalue: layer?.isovalue, - opacity: layer?.opacity, - visible: layer?.visible, - color: layer?.color, - negativeColor: layer?.negative_color, - showNegative: layer?.show_negative, - colorVolumeIndex: layer?.color_volume_idx, - colormap: typeof layer?.colormap === 'string' ? layer.colormap : undefined, - colorRange: range && range[0] <= range[1] ? range : range ? [range[1], range[0]] : undefined, - } - }), - periodic: input.manifest.periodic?.enabled ? { - displayRange: validDisplayRange, - atomSupercell: input.atomSupercell, - showBoundaryAtoms: input.showBoundaryAtoms, - showUnitCell: input.showUnitCell, - } : undefined, - camera: normalize_camera(input.camera), - isosurface: appearance, - structureAppearance, - slice: normalize_slice(input.slice), - espLegend: normalize_legend(input.espLegend), - topologyDisplay: input.topologyDisplay ? normalize_topology_display(input.topologyDisplay) : undefined, - session: { - multiwfnGui: input.manifest.multiwfnGui, - bondAnalysis: input.manifest.bondAnalysis, - espAnalysis: input.manifest.espAnalysis, - }, - } -} - -/** Parse a version-1 workbench snapshot, rejecting unsupported required fields. */ -export const parse_workbench_state = (value: unknown): MatterVizWorkbenchState => { - const root = as_record(value) - if (root.format !== 'multiwfn-matterviz-workbench') throw new Error('Unsupported workbench state format') - if (root.version !== 1) throw new Error('Unsupported workbench state version') - if (!Array.isArray(root.volumes)) throw new Error('Workbench state is missing volumes') - - const volumes = root.volumes - .map(normalize_layer_snapshot) - .filter((entry): entry is MatterVizWorkbenchState['volumes'][number] => Boolean(entry)) - const activeVolume = finite_integer(root.activeVolume) ?? 0 - const sourceManifest = typeof root.sourceManifest === 'string' ? root.sourceManifest : undefined - - const periodicRecord = as_record(root.periodic) - const atomSupercell = typeof periodicRecord.atomSupercell === 'string' ? periodicRecord.atomSupercell : undefined - const showBoundaryAtoms = typeof periodicRecord.showBoundaryAtoms === 'boolean' - ? periodicRecord.showBoundaryAtoms : undefined - const showUnitCell = typeof periodicRecord.showUnitCell === 'boolean' ? periodicRecord.showUnitCell : undefined - const displayRangeValue = Array.isArray(periodicRecord.displayRange) - ? periodicRecord.displayRange.map(finite_pair) - : undefined - const displayRange = displayRangeValue?.length === 3 && displayRangeValue.every(Boolean) - ? displayRangeValue as [[number, number], [number, number], [number, number]] - : undefined - const periodic = atomSupercell !== undefined && showBoundaryAtoms !== undefined && showUnitCell !== undefined - ? { displayRange, atomSupercell, showBoundaryAtoms, showUnitCell } - : undefined - - const sessionRecord = as_record(root.session) - const session = { - multiwfnGui: record_or_undefined(sessionRecord.multiwfnGui) as MultiwfnManifest['multiwfnGui'], - bondAnalysis: record_or_undefined(sessionRecord.bondAnalysis) as MultiwfnManifest['bondAnalysis'], - espAnalysis: record_or_undefined(sessionRecord.espAnalysis) as MultiwfnManifest['espAnalysis'], - } - return { - format: 'multiwfn-matterviz-workbench', - version: 1, - sourceManifest, - representations: root.representations === undefined ? undefined : normalize_reps(root.representations), - activeVolume: Math.min(Math.max(0, volumes.length - 1), Math.max(0, activeVolume)), - volumes, - periodic, - camera: normalize_camera(root.camera), - isosurface: normalize_appearance(root.isosurface), - structureAppearance: normalize_structure_appearance(root.structureAppearance), - slice: normalize_slice(root.slice), - espLegend: normalize_legend(root.espLegend), - topologyDisplay: root.topologyDisplay ? normalize_topology_display(root.topologyDisplay) : undefined, - session, - } -} - -const clamp_index = (value: number, count: number): number => - count > 0 ? Math.min(count - 1, Math.max(0, Math.trunc(value))) : 0 - -const restore_layer = ( - current: IsosurfaceLayer, - snapshot: MatterVizWorkbenchState['volumes'][number] | undefined, - volumeCount: number, -): IsosurfaceLayer => { - if (!snapshot) return { ...current } - const layer: IsosurfaceLayer = { ...current } - if (snapshot.isovalue !== undefined && Number.isFinite(snapshot.isovalue)) layer.isovalue = snapshot.isovalue - if (snapshot.opacity !== undefined && Number.isFinite(snapshot.opacity)) layer.opacity = Math.min(1, Math.max(0, snapshot.opacity)) - if (snapshot.visible !== undefined) layer.visible = snapshot.visible - if (snapshot.color !== undefined) layer.color = snapshot.color - if (snapshot.negativeColor !== undefined) layer.negative_color = snapshot.negativeColor - if (snapshot.showNegative !== undefined) layer.show_negative = snapshot.showNegative - if (snapshot.colormap !== undefined) layer.colormap = snapshot.colormap as IsosurfaceLayer['colormap'] - if (snapshot.colorRange !== undefined) layer.color_range = [...snapshot.colorRange] as IsosurfaceLayer['color_range'] - if (snapshot.colorVolumeIndex !== undefined - && Number.isInteger(snapshot.colorVolumeIndex) - && snapshot.colorVolumeIndex >= 0 - && snapshot.colorVolumeIndex < volumeCount) { - layer.color_volume_idx = clamp_index(snapshot.colorVolumeIndex, volumeCount) - } - return layer -} - -/** Restore a snapshot's appearance and UI state onto currently loaded volumes. */ -export const restore_workbench_state = ( - state: MatterVizWorkbenchState, - input: { entries: ManifestEntry[]; isosurfaceSettings: IsosurfaceSettings }, -): WorkbenchStateRestoration => { - const snapshots = new Map(state.volumes.map((volume) => [volume.volumeIndex, volume])) - const layers = (input.isosurfaceSettings.layers ?? []).map((layer, index) => { - const volumeIndex = layer.volume_idx ?? index - return restore_layer(layer, snapshots.get(volumeIndex), input.entries.length) - }) - const isosurfaceSettings: IsosurfaceSettings = { - ...input.isosurfaceSettings, - layers, - } - const appearance = normalize_appearance(state.isosurface) - if (appearance) { - if (appearance.wireframe !== undefined) isosurfaceSettings.wireframe = appearance.wireframe - if (appearance.material !== undefined) isosurfaceSettings.material = appearance.material - if (appearance.flatShading !== undefined) isosurfaceSettings.flat_shading = appearance.flatShading - for (const key of ['roughness', 'metalness', 'shininess', 'specular', 'halo', 'outline', 'outlineWidth', 'transmode'] as const) { - const value = appearance[key] - if (value !== undefined && Number.isFinite(value)) isosurfaceSettings[key] = value - } - } - return { - activeVolume: clamp_index(state.activeVolume, input.entries.length), - representations: state.representations ? remap_rep_sources(state.representations, input.entries) : undefined, - isosurfaceSettings, - periodic: state.periodic, - camera: state.camera, - structureAppearance: normalize_structure_appearance(state.structureAppearance), - slice: state.slice, - espLegend: state.espLegend, - topologyDisplay: state.topologyDisplay, - } -} - -export const download_workbench_state = (state: MatterVizWorkbenchState): void => { - const blob = new Blob([`${JSON.stringify(state, null, 2)}\n`], { type: 'application/json' }) - const url = URL.createObjectURL(blob) - const link = document.createElement('a') - link.href = url - link.download = 'multiwfn-matterviz-state.json' - link.click() - URL.revokeObjectURL(url) -} diff --git a/frontend/matterviz-viewer/src/styles.css b/frontend/matterviz-viewer/src/styles.css index d627e7ce..37e76973 100644 --- a/frontend/matterviz-viewer/src/styles.css +++ b/frontend/matterviz-viewer/src/styles.css @@ -220,7 +220,6 @@ button:disabled { opacity: 0.45; cursor: default; } width: 100% !important; height: 100% !important; } -.scene-viewport .measure-label { display: none !important; } .scene-readouts { min-width: 0; max-height: 140px; overflow: auto; border-top: 1px solid #cfd6df; background: #f8f9fb; color: #18202a; } .calculation-status { display: flex; align-items: center; gap: 10px; min-height: 36px; padding: 6px 10px; font-size: 12px; } .calculation-status progress { width: 56px; height: 8px; flex: 0 0 56px; } diff --git a/frontend/matterviz-viewer/src/volume-cache.ts b/frontend/matterviz-viewer/src/volume-cache.ts deleted file mode 100644 index 1261b302..00000000 --- a/frontend/matterviz-viewer/src/volume-cache.ts +++ /dev/null @@ -1,135 +0,0 @@ -import type { IsosurfaceLayer } from 'matterviz' -import type { ManifestEntry } from './manifest' - -type VolumeWithGrid = { - grid?: unknown -} - -export type VolumeCacheState = { - volumes: Volume[] - entries: ManifestEntry[] - layers: IsosurfaceLayer[] - active_volume_idx: number -} - -export type VolumeCacheOptions = { - remove_indices?: Iterable - retain_indices?: Iterable - retain_active_volume?: boolean -} - -export type CompactedVolumeCache = VolumeCacheState & { - old_to_new: Map - released_volumes: Volume[] - released_buffers: Set -} - -const volume_buffer = (volume: VolumeWithGrid): ArrayBufferLike | undefined => { - const grid = volume.grid as { data?: { buffer?: ArrayBufferLike } } | undefined - return grid?.data?.buffer -} - -const valid_index = (value: unknown, length: number): value is number => - Number.isInteger(value) && Number(value) >= 0 && Number(value) < length - -const is_orbital = (entry: ManifestEntry | undefined): boolean => - entry?.role?.toLowerCase() === 'orbital' - -/** Keep non-orbital visibility intact while selecting at most one orbital layer. */ -export const orbital_visibility = ( - layers: Layer[], - entries: ManifestEntry[], - active_volume_idx: number | undefined, -): Layer[] => layers.map((layer) => { - const volume_idx = layer.volume_idx ?? 0 - if (!is_orbital(entries[volume_idx])) return { ...layer } - return { ...layer, visible: active_volume_idx === volume_idx } -}) - -/** - * Drop unreferenced volume objects and rebuild every index in one atomic result. - * Releasing means removing application strong references; JS owns the eventual - * ArrayBuffer/SAB reclamation while MatterViz disposes derived GPU geometry. - */ -export const compact_volume_cache = ( - state: VolumeCacheState, - options: VolumeCacheOptions = {}, -): CompactedVolumeCache => { - const length = Math.min(state.volumes.length, state.entries.length) - const removed = new Set( - [...(options.remove_indices ?? [])].filter((index) => valid_index(index, length)), - ) - const retained = new Set() - const retain = (index: unknown): boolean => { - if (!valid_index(index, length) || removed.has(index)) return false - retained.add(index) - return true - } - - for (const index of options.retain_indices ?? []) retain(index) - if (options.retain_active_volume !== false) retain(state.active_volume_idx) - for (const layer of state.layers) { - const volume_idx = layer.volume_idx ?? 0 - if (layer.visible !== false) retain(volume_idx) - } - - // A retained surface owns its color source even when the source layer itself - // is hidden. Iterate to a fixed point for future chained references. - let changed = true - while (changed) { - changed = false - for (const layer of state.layers) { - const owner = layer.volume_idx ?? 0 - if (!retained.has(owner) || layer.color_volume_idx === undefined) continue - const before = retained.size - retain(layer.color_volume_idx) - changed ||= retained.size !== before - } - } - - const old_to_new = new Map() - const volumes: Volume[] = [] - const entries: ManifestEntry[] = [] - for (let index = 0; index < length; index += 1) { - if (!retained.has(index)) continue - old_to_new.set(index, volumes.length) - volumes.push(state.volumes[index]) - entries.push(state.entries[index]) - } - - const layers = state.layers.flatMap((layer) => { - const volume_idx = old_to_new.get(layer.volume_idx ?? 0) - if (volume_idx === undefined) return [] - const color_volume_idx = layer.color_volume_idx === undefined - ? undefined - : old_to_new.get(layer.color_volume_idx) - return [{ - ...layer, - volume_idx, - ...(layer.color_volume_idx === undefined ? {} : { color_volume_idx }), - ...(layer.color_volume_idx !== undefined && color_volume_idx === undefined - ? { colormap: undefined, color_range: undefined } - : {}), - }] - }) - - const released_volumes = state.volumes.slice(0, length) - .filter((_volume, index) => !retained.has(index)) - const retained_buffers = new Set(volumes.map(volume_buffer).filter((buffer) => buffer !== undefined)) - const released_buffers = new Set() - for (const volume of released_volumes) { - const buffer = volume_buffer(volume) - if (buffer && !retained_buffers.has(buffer)) released_buffers.add(buffer) - } - - const mapped_active = old_to_new.get(state.active_volume_idx) - return { - volumes, - entries, - layers, - active_volume_idx: mapped_active ?? Math.min(state.active_volume_idx, Math.max(0, volumes.length - 1)), - old_to_new, - released_volumes, - released_buffers, - } -} diff --git a/frontend/matterviz-viewer/src/volume-mapping.ts b/frontend/matterviz-viewer/src/volume-mapping.ts deleted file mode 100644 index f37ce1f0..00000000 --- a/frontend/matterviz-viewer/src/volume-mapping.ts +++ /dev/null @@ -1,29 +0,0 @@ -import type { IsosurfaceLayer } from 'matterviz/isosurface' -import { normalize_color_stops } from 'matterviz/colors/stops' -import type { ManifestEntry } from './manifest.ts' - -/** A surface and its coloring field are separate datasets; never infer a pair - * from array order or from the sign/range of the sampled values. */ -export const apply_manifest_color_mapping = ( - layers: IsosurfaceLayer[], - entries: ManifestEntry[], - compatible: (surface: number, color: number) => boolean, -): IsosurfaceLayer[] => layers.map((layer) => { - const surfaceIdx = layer.volume_idx ?? 0 - const mapping = entries[surfaceIdx]?.colorMapping - if (!mapping) return layer - const colorIdx = entries.findIndex((entry) => entry.path === mapping.path) - if (colorIdx < 0 || colorIdx === surfaceIdx || !compatible(surfaceIdx, colorIdx)) { - throw new Error('The mapped surface needs a separate coloring dataset on the same grid') - } - const range = mapping.range - if (!Array.isArray(range) || range.length !== 2 || !range.every(Number.isFinite) || range[0] >= range[1]) { - throw new Error('The mapped surface color range must have finite, increasing bounds') - } - return { - ...layer, - color_volume_idx: colorIdx, - color_range: [...range], - color_stops: normalize_color_stops(mapping.stops), - } -}) diff --git a/frontend/matterviz-viewer/src/volume.ts b/frontend/matterviz-viewer/src/volume.ts index 93755eba..8581808d 100644 --- a/frontend/matterviz-viewer/src/volume.ts +++ b/frontend/matterviz-viewer/src/volume.ts @@ -1,3 +1,4 @@ +import { BOHR_TO_ANGSTROM } from 'matterviz/constants' import type { VolumetricData } from 'matterviz/isosurface' export type Vec3 = [number, number, number] @@ -38,7 +39,6 @@ const VOLUME_HEADER_BYTES = 304 const MAX_POINTS = 1_500_000n const MAX_BODY_BYTES = 12_000_000n const MAX_FRAME_BYTES = 12_000_304n -const BOHR_TO_ANGSTROM = 0.529177249 const NATIVE_LITTLE_ENDIAN = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1 const VOLUME_MAGIC = [0x4d, 0x57, 0x46, 0x4e, 0x56, 0x4f, 0x4c, 0x00] as const @@ -312,8 +312,8 @@ export function decode_matterviz_volume(input: ArrayBufferLike | Uint8Array): Ma } } -/** Convert a decoded frame to MatterViz volumetric data without copying samples. */ -export function adapt_matterviz_volume(volume: MattervizVolumeV1): VolumetricData { +/** MatterViz consumes flat C-order values. Cube-order frames can share their sample buffer. */ +export function adapt_matterviz_volume(volume: MattervizVolumeV1, id = String(volume.volume_id)): VolumetricData { const [nx, ny, nz] = volume.dimensions const periodic_axis_count = volume.periodic_axes.filter(Boolean).length if (periodic_axis_count !== 0 && periodic_axis_count !== 3) { @@ -331,18 +331,24 @@ export function adapt_matterviz_volume(volume: MattervizVolumeV1): VolumetricDat if (grid_lattice.flat().some((value) => !Number.isFinite(value))) { throw new Error('MatterViz volume grid lattice must be finite') } + let values = volume.samples + if (volume.data_order === 'i_fastest_fortran') { + values = new Float64Array(volume.samples.length) + for (let x = 0; x < nx; x++) { + for (let y = 0; y < ny; y++) { + for (let z = 0; z < nz; z++) { + values[(x * ny + y) * nz + z] = volume.samples[(z * ny + y) * nx + x] + } + } + } + } return { - grid: { - data: volume.samples, - dimensions: volume.dimensions, - order: volume.data_order === 'i_fastest_fortran' ? 'x-fastest' : 'z-fastest', - }, - grid_dims: volume.dimensions, + id, values, dims: volume.dimensions, order: 'z_fastest', lattice: grid_lattice, origin: scale_vec3(volume.origin, scale), - origin_mode: 'absolute', data_range: volume.statistics, - data_order: volume.data_order === 'i_fastest_fortran' ? 'x_fastest' : 'z_fastest', + units: volume.value_unit, + signed: volume.quantity_kind !== 'electron_density', periodic: periodic_axis_count === 3, } } diff --git a/frontend/matterviz-viewer/tests/analysis-structure.test.ts b/frontend/matterviz-viewer/tests/analysis-structure.test.ts index ff2a4afd..ab52f8ac 100644 --- a/frontend/matterviz-viewer/tests/analysis-structure.test.ts +++ b/frontend/matterviz-viewer/tests/analysis-structure.test.ts @@ -1,8 +1,6 @@ import assert from 'node:assert/strict' -import { execFileSync } from 'node:child_process' import { readFile } from 'node:fs/promises' import test from 'node:test' -import { compileModule } from 'svelte/compiler' import type { AnyStructure } from 'matterviz' import { analysis_structure_key } from '../src/analysis-structure.ts' @@ -43,95 +41,9 @@ test('display labels, properties, derived cell dimensions and species ordering d assert.equal(key(changed), key(original)) }) -test('production manifest loaders discard stale analysis but finish startup; failed loads do not signal ready', async () => { - const source = await readFile(new URL('../src/App.svelte', import.meta.url), 'utf8') - const effectStart = source.indexOf(' $effect(() => {\n if (loadedGeometryKey') - const effectEnd = source.indexOf(' let displayedStructure', effectStart) - const loadStart = source.indexOf(' if (manifest.topology) {') - const loadEnd = source.indexOf(" if (String(manifest.multiwfnGui?.entry", loadStart) - const finishStart = source.indexOf(" set_status(surfaceResult ? ui_message('Original quantitative surface results loaded')", loadEnd) - const finishEnd = source.indexOf('\n }', finishStart) - const derived = source.split('\n').find((line) => line.includes('const geometryKey = $derived'))! - assert.ok(effectStart > 0 && effectEnd > effectStart && loadStart > 0 && loadEnd > loadStart - && finishStart > loadEnd && finishEnd > finishStart) - // Exercise both production loader blocks and the real completion/catch/finally - // path. A stale result must not prevent the native startup-ready handshake. - const code = ` - import assert from 'node:assert/strict' - import { flushSync } from 'svelte' - import { analysis_structure_key } from './src/analysis-structure.ts' - import { ui_message, format_message } from './src/i18n.ts' - async function exercise(stage, change, reject = false) { - let topologyGeneration = 0 - let structure = $state(${JSON.stringify(fixture())}) - let loadedGeometryKey = $state(analysis_structure_key(structure)) - ${derived} - let topologyResult = $state.raw(), topologyActive = $state(false), topologySelection = $state() - let surfaceResult = $state.raw(), surfaceActive = $state(false), surfaceSelection = $state() - let surfacePanelOpen = $state(false), topologyPanelOpen = $state(false), orbitalPanelOpen = $state(true) - let surfaceFitPending = false, loading = true, readyCalls = 0, restoredCalls = 0, status = '' - const errors = [] - const set_status = value => status = value - const signal_frontend_ready = async () => readyCalls++ - const report_error = error => errors.push(error.message) - const startupState = {}, entries = [] - const apply_workbench_state = () => restoredCalls++ - const open_surface_results = () => { surfaceActive = true; surfacePanelOpen = true } - const cleanup = $effect.root(() => { ${source.slice(effectStart, effectEnd)} }) - flushSync() - let finishTopology, rejectTopology, finishSurface, rejectSurface - const load_topology = () => new Promise((resolve, reject) => { finishTopology = resolve; rejectTopology = reject }) - const load_surface = () => new Promise((resolve, reject) => { finishSurface = resolve; rejectSurface = reject }) - const manifest = { topology: {}, surfaceAnalysis: {} } - const generation = topologyGeneration - const request = async () => { - try { - ${source.slice(loadStart, loadEnd)} - ${source.slice(finishStart, finishEnd)} - } - const edit = () => { - if (change === 'coordinates') structure.sites[0].xyz[0] = 10 - if (change === 'species') structure.sites[0].species[0].element = 'O' - if (change === 'lattice') structure.lattice.matrix[0][0] = 6 - if (change === 'generation') topologyGeneration++ - flushSync() - } - const pending = request() - if (stage === 'topology') edit() - if (reject && stage === 'topology') rejectTopology(new Error('topology failed')) - else { - finishTopology({ source: 'topology' }) - await Promise.resolve() - if (stage === 'surface') edit() - if (reject) rejectSurface(new Error('surface failed')) - else finishSurface({ source: 'surface' }) - } - await pending - flushSync() - assert.equal(loading, false) - assert.equal(readyCalls, reject ? 0 : 1, stage + ':' + change + ' readiness') - assert.equal(restoredCalls, reject ? 0 : 1) - if (reject) { - assert.deepEqual(errors, [stage + ' failed']) - assert.equal(format_message('en', status), 'Session loading failed') - } else { - assert.deepEqual(errors, []) - assert.equal(Boolean(surfaceResult), !change) - assert.equal(surfaceActive, !change) - assert.equal(surfaceFitPending, !change) - const topologyExpected = !change || (stage === 'surface' && change === 'generation') - assert.equal(Boolean(topologyResult), topologyExpected) - assert.equal(topologyActive, topologyExpected) - } - cleanup() - } - for (const stage of ['topology', 'surface']) { - for (const change of ['', 'coordinates', 'species', 'lattice', 'generation']) await exercise(stage, change) - await exercise(stage, '', true) - } - ` - const compiled = compileModule(code, { filename: 'analysis-lifetime.svelte.js', generate: 'client' }) - execFileSync(process.execPath, ['--conditions=browser', '--experimental-strip-types', '--input-type=module'], { - input: compiled.js.code, cwd: new URL('..', import.meta.url), timeout: 15000, stdio: 'pipe', - }) +test('native readiness follows both scene and plot loading', async () => { + const app = await readFile(new URL('../src/App.svelte', import.meta.url), 'utf8') + const load = app.slice(app.indexOf('async function load_manifest()'), app.indexOf('function show_orbital')) + assert.ok(load.indexOf('await signal_frontend_ready()') > load.indexOf('await load_surface(')) + assert.match(load, /await signal_frontend_ready\(\)\s*\} catch/) }) diff --git a/frontend/matterviz-viewer/tests/atom-style.test.ts b/frontend/matterviz-viewer/tests/atom-style.test.ts deleted file mode 100644 index 8ff26e9e..00000000 --- a/frontend/matterviz-viewer/tests/atom-style.test.ts +++ /dev/null @@ -1,19 +0,0 @@ -import assert from 'node:assert/strict' -import test from 'node:test' -import { apply_atom_style, ATOM_STYLE_PRESETS, atom_style_values, normalize_atom_style } from '../src/atom-style.ts' -import { create_workbench_state, parse_workbench_state, restore_workbench_state } from '../src/state.ts' - -test('TMIM atom presets retain the historical six parameter combinations', () => { - assert.deepEqual(ATOM_STYLE_PRESETS.map((p) => p.value), ['current', 'goodsell', 'edgy', 'glass', 'metallic', 'matte']) - assert.deepEqual(ATOM_STYLE_PRESETS.find((p) => p.value === 'current'), { value: 'current', label: 'Balanced', roughness: .5, metalness: .07, opacity: 1, outline: .1, outlineWidth: .6 }) - assert.deepEqual(ATOM_STYLE_PRESETS.find((p) => p.value === 'glass'), { value: 'glass', label: 'Glass', roughness: .05, metalness: 0, opacity: .55, outline: .05, outlineWidth: .6 }) - assert.deepEqual(normalize_atom_style({ atom_roughness: -1, atom_metalness: 3, atom_opacity: '0.4', atom_outline: 2, atom_outline_width: 2 }), { atom_roughness: 0, atom_metalness: 1, atom_opacity: .4, atom_outline: 1, atom_outline_width: 1 }) -}) - -test('TMIM atom appearance persists through a portable workbench snapshot', () => { - const scene = apply_atom_style({ lighting_rig: 'tmim', scene_tone_mapping: 'none', ambient_light: 1.25, directional_light: 1.55, fill_light: .85, rim_light: .42 }, 'glass') - const snapshot = create_workbench_state({ manifest: {}, entries: [{ path: 'structure.json' }], activeVolume: 0, atomSupercell: '1x1x1', showBoundaryAtoms: true, showUnitCell: false, isosurfaceSettings: {}, sceneProps: scene }) - const restored = restore_workbench_state(parse_workbench_state(JSON.parse(JSON.stringify(snapshot))), { entries: [{ path: 'structure.json' }], isosurfaceSettings: {} }) - assert.deepEqual(restored.structureAppearance, { ambientLight: 1.25, directionalLight: 1.55, fillLight: .85, rimLight: .42, lightingRig: 'tmim', sceneToneMapping: 'none', atomStyle: 'glass', atomMaterial: 'pbr', atomRoughness: .05, atomMetalness: 0, atomOpacity: .55, atomOutline: .05, atomOutlineWidth: .6 }) - assert.equal(atom_style_values(scene).value, 'glass') -}) diff --git a/frontend/matterviz-viewer/tests/bond-interaction-contract.test.ts b/frontend/matterviz-viewer/tests/bond-interaction-contract.test.ts deleted file mode 100644 index be5daca6..00000000 --- a/frontend/matterviz-viewer/tests/bond-interaction-contract.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -import assert from 'node:assert/strict' -import { readFile } from 'node:fs/promises' -import test from 'node:test' - -const appSource = (): Promise => - readFile(new URL('../src/App.svelte', import.meta.url), 'utf8') - -test('Multiwfn configures ordered distance and angle/dihedral measurement', async () => { - const source = await appSource() - - assert.ok(source.includes('show_atom_tooltip={false}')) - assert.ok(source.includes("distance: { max_sites: 2, overflow: 'restart' }")) - assert.ok(source.includes("angle: { max_sites: 4, overflow: 'reject' }")) - assert.ok(source.includes('measure_geometry="ordered"')) - assert.ok(source.includes('on_selected_bond_context={open_bond_context_menu}')) - assert.ok(source.includes('bind:displayed_structure={displayedStructure}')) -}) - -test('bond calculations require exactly two source atoms and context requests snapshot the pair', async () => { - const source = await appSource() - - assert.ok(source.includes('if (sites.length !== 2) return undefined')) - assert.ok(source.includes('pair.every((siteIndex) => siteIndex < Number(sourceSiteCount))')) - assert.ok(source.includes('orig_unit_cell_idx ?? properties?.orig_site_idx ?? siteIndex')) - assert.ok(source.includes("!selected_source_bond_pair() ? 'Use the measurement tool to select two atoms'")) - const action = await readFile(new URL('../src/AnalysisAction.svelte', import.meta.url), 'utf8') - assert.ok(action.includes('disabled={busy || Boolean(reason)}')) - - const snapshot = source.indexOf('const pair = menu ? valid_source_bond_pair(menu.source_site_indices) : undefined') - const closeMenu = source.indexOf('close_bond_context_menu()', snapshot) - const request = source.indexOf('await request_bond({ method, pair: [...pair] })', snapshot) - assert.ok(snapshot >= 0, 'context-menu requests must capture their source atom pair') - assert.ok(closeMenu > snapshot, 'the context menu should close after capturing its atom pair') - assert.ok(request > closeMenu, 'the captured pair should be passed to the bond request') -}) - -test('bond-order context menu exposes disabled reasons and standard dismissal behavior', async () => { - const source = await appSource() - - for (const [method, label] of [ - ['mayer', 'Mayer'], - ['gwbo', 'GWBO'], - ['wiberg_lowdin', 'Wiberg-Löwdin'], - ['mulliken', 'Mulliken'], - ['fbo', 'FBO'], - ]) { - assert.ok(source.includes(`${method}: '${label}'`), `${method} should have a human-readable label`) - } - assert.ok(source.includes(".replace(/[_-]+/g, ' ')"), 'unknown method keys should have a readable fallback') - assert.ok(source.includes('{bond_method_label(method)}')) - assert.ok(source.includes('class="bond-analysis-menu"')) - assert.ok(source.includes('role="menu"')) - assert.ok(source.includes('role="menuitem"')) - assert.ok(source.includes('aria-disabled={Boolean(unavailableReason)}')) - assert.ok(source.includes('{#each Object.entries(manifest.bondAnalysis.methods) as [method, capability]}')) - assert.ok(source.includes('{#if unavailableReason}{$t(capability.reason || unavailableReason)}{/if}')) - assert.ok(source.includes('bondMethod = method')) - assert.ok(source.includes("event.key === 'Escape'")) - assert.ok(source.includes("document.addEventListener('pointerdown', close_on_outside_pointer, true)")) -}) diff --git a/frontend/matterviz-viewer/tests/browser/TopologyPicking.svelte b/frontend/matterviz-viewer/tests/browser/TopologyPicking.svelte deleted file mode 100644 index baf57526..00000000 --- a/frontend/matterviz-viewer/tests/browser/TopologyPicking.svelte +++ /dev/null @@ -1,67 +0,0 @@ - -
- - contexts.push(detail)} /> - -
diff --git a/frontend/matterviz-viewer/tests/browser/color-scale.mjs b/frontend/matterviz-viewer/tests/browser/color-scale.mjs deleted file mode 100644 index 58a0ef0c..00000000 --- a/frontend/matterviz-viewer/tests/browser/color-scale.mjs +++ /dev/null @@ -1,218 +0,0 @@ -// Editable scales against real density/ESP geometry, pixels and saved scenes. -import assert from 'node:assert/strict' -import { mkdir, readFile, writeFile } from 'node:fs/promises' -import path from 'node:path' -const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright') -const preview = process.env.PREVIEW_URL || 'http://127.0.0.1:5297/?manifest=/session/surface-manifest.json' -const artifacts = process.env.ARTIFACT_DIR || '/tmp/multiwfn-color-scale' -await mkdir(artifacts, { recursive: true }) -const browser = await chromium.launch({ executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE, - headless: true, args: ['--no-sandbox', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'] }) -const page = await browser.newPage({ viewport: { width: 1280, height: 900 }, locale: 'en-US', acceptDownloads: true }) -page.setDefaultTimeout(30000) -const errors = [], checks = [] -page.on('pageerror', error => errors.push(String(error))) -page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()) }) -const button = name => page.getByRole('button', { name, exact: true }) -const input = name => page.getByRole('spinbutton', { name, exact: true }) -const select = name => page.getByRole('combobox', { name, exact: true }) -const position = index => input(`Position of color stop ${index} (%)`) -const hex = index => page.getByRole('textbox', { name: `Hex color of stop ${index}`, exact: true }) -const edit = async (locator, value) => { await locator.fill(String(value)); await locator.press('Tab') } -const record = message => { checks.push(message); console.log('PASS', message) } -const capture = async name => { - await page.waitForTimeout(200) - const result = await page.evaluate(() => { - const { scene, camera } = window.scaleScene, renderer = window.scaleRenderer - let colorHash = 2166136261, vertices = 0 - const geometry = new Set() - scene.getObjectByName('rep-copies-volume-1').traverse(mesh => { - if (!mesh.isMesh || geometry.has(mesh.geometry.uuid)) return - geometry.add(mesh.geometry.uuid) - const color = mesh.geometry.getAttribute('color') - vertices += color.count - for (const byte of new Uint8Array(color.array.buffer, color.array.byteOffset, color.array.byteLength)) colorHash = Math.imul(colorHash ^ byte, 16777619) - }) - renderer.render(scene, camera) - const canvas = document.createElement('canvas'), source = renderer.domElement - canvas.width = source.width; canvas.height = source.height - const context = canvas.getContext('2d'); context.drawImage(source, 0, 0) - let pixelHash = 2166136261 - for (const byte of context.getImageData(0, 0, canvas.width, canvas.height).data) pixelHash = Math.imul(pixelHash ^ byte, 16777619) - return { geometry: [...geometry], colorHash, pixelHash, vertices, - camera: [camera.position.toArray(), camera.quaternion.toArray(), camera.zoom], png: canvas.toDataURL('image/png') } - }) - if (name) await writeFile(path.join(artifacts, `${name}.png`), Buffer.from(result.png.split(',')[1], 'base64')) - delete result.png - assert.ok(result.vertices > 100, 'real mapped surface is present') - return result -} -const save = async name => { - await button('Save').click() - const download = page.waitForEvent('download'); await button('Save display settings').click() - const file = path.join(artifacts, `${name}.json`); await (await download).saveAs(file) - return JSON.parse(await readFile(file, 'utf8')) -} -try { - await page.goto(preview, { waitUntil: 'networkidle', timeout: 180000 }) - await page.locator('.rep-row').first().waitFor() - await page.evaluate(async () => { - const url = performance.getEntriesByType('resource').map(e => e.name).find(url => /\/matterviz\.js/.test(url)) - const mv = window.scaleMatterviz = await import(url), canvas = document.querySelector('.structure canvas') - window.scaleScene = mv.scene_registry.get(canvas); window.scaleRenderer = mv.renderer_registry.get(canvas) - }) - await page.waitForFunction(() => window.scaleScene.scene.getObjectByName('rep-copies-volume-1')?.children[0]?.children.length > 0) - await page.locator('.rep-select').nth(1).click() - await select('Color scale').selectOption('interpolateViridis') - assert.equal(await page.locator('.scale-stop').count(), 0) - assert.equal(await button('Add color stop').count(), 0) - assert.equal(await select('Load preset').count(), 0) - const viridis = await capture() - await select('Color scale').selectOption('custom') - assert.equal(await page.locator('.scale-stop').count(), 9) - assert.equal(await hex(1).inputValue(), '#440154') - assert.equal((await capture()).colorHash, viridis.colorHash, 'entering custom mode retains the selected preset colors') - await select('Load preset').selectOption('interpolateTransFlag') - assert.equal(await select('Color scale').inputValue(), 'custom') - assert.equal(await page.locator('.scale-stop').count(), 3) - await select('Load preset').selectOption('interpolateViridis') - assert.equal(await page.locator('.scale-stop').count(), 9) - await select('Color scale').selectOption('interpolateTransFlag') - assert.equal(await page.locator('.scale-stop').count(), 0) - assert.equal(await select('Load preset').count(), 0) - await page.locator('.color-scale-editor').scrollIntoViewIfNeeded() - await page.screenshot({ path: path.join(artifacts, 'color-scale-preset.png'), animations: 'disabled' }) - await select('Color scale').selectOption('custom') - assert.equal(await page.locator('.scale-stop').count(), 3) - record('Named presets hide editing controls; Custom keeps current colors and can load another preset while staying editable') - const before = await capture('preset') - await edit(position(2), 20) - assert.equal(await select('Color scale').inputValue(), 'custom') - await edit(hex(1), '#ff0000'); await edit(hex(2), '#00ff00'); await edit(hex(3), '#0000ff') - const changed = await capture('custom') - assert.deepEqual(changed.geometry, before.geometry, 'color edits retain the extracted mesh') - assert.deepEqual(changed.camera, before.camera) - assert.notEqual(changed.colorHash, before.colorHash) - assert.notEqual(changed.pixelHash, before.pixelHash) - record('Preset control points are editable; uneven positions and hex colors recolor actual surface pixels without rebuilding geometry') - - await button('Add color stop').click() - assert.equal(await page.locator('.scale-stop').count(), 4) - assert.equal(await position(3).inputValue(), '60') - await button('Remove color stop 3').click() - assert.equal((await capture()).colorHash, changed.colorHash) - await edit(position(2), 0) - assert.match(await page.getByRole('alert').innerText(), /distinct/) - assert.equal(await position(2).inputValue(), '20') - assert.equal((await capture()).colorHash, changed.colorHash) - await edit(hex(2), '#zzzzzz') - assert.match(await page.getByRole('alert').innerText(), /six-digit/) - assert.equal(await hex(2).inputValue(), '#00ff00') - await edit(position(1), 70) - assert.equal(await position(1).inputValue(), '20') - assert.equal(await hex(1).inputValue(), '#00ff00', 'sorting keeps each position paired with its own color') - await edit(position(2), 0) - record('Add/remove, automatic sorting and invalid/duplicate position or color feedback preserve valid state') - - if (!(await page.locator('.esp-legend').isVisible())) { - await button('Tools').click(); await button('ESP legend').click(); await button('Tools').click() - } - const legendGradient = await page.locator('.legend-gradient').evaluate(el => el.style.backgroundImage) - assert.match(legendGradient, /rgb\(0, 255, 0\) 20%/) - assert.equal(legendGradient, (await page.locator('.scale-preview').evaluate(el => el.style.backgroundImage)).replace('to right', 'to top')) - await page.getByRole('checkbox', { name: 'Manual color range', exact: true }).uncheck() - // Independently sample the real ESP cube at the extracted surface vertices. - const actualRange = await page.evaluate(async () => { - const mv = window.scaleMatterviz, manifestUrl = new URL(new URL(location.href).searchParams.get('manifest'), location.href) - const manifest = await (await fetch(manifestUrl)).json() - const volumes = await Promise.all(manifest.cubes.map(async entry => mv.parse_cube(await (await fetch(new URL(entry.path, manifestUrl))).text()).volumes[0])) - const sample = mv.create_volume_sampler(volumes[1], { out_of_bounds: 'fallback' }), arrays = [], seen = new Set() - const origin = manifest.structure?.path ? [0, 0, 0] : volumes[0].origin - window.scaleScene.scene.getObjectByName('rep-copies-volume-1').traverse(mesh => { - if (!mesh.isMesh || seen.has(mesh.geometry.uuid)) return - seen.add(mesh.geometry.uuid) - const positions = mesh.geometry.getAttribute('position'), values = new Float32Array(positions.count) - for (let i = 0; i < positions.count; i++) values[i] = sample([positions.getX(i) + origin[0], positions.getY(i) + origin[1], positions.getZ(i) + origin[2]]) - arrays.push(values) - }) - return mv.compute_scalar_range(arrays, { symmetric: mv.is_signed_range(volumes[1].data_range) }) - }) - await page.waitForFunction(expected => document.querySelector('.esp-legend footer')?.textContent.includes(expected), Number(actualRange[0]).toPrecision(5)) - assert.ok((await page.locator('.esp-legend footer').innerText()).includes(Number(actualRange[1]).toPrecision(5))) - record('Legend uses the same stop positions and actual surface-fitted range, verified from ESP samples') - - const original = await save('single-scale') - const originalScale = original.representations.items.find(rep => rep.id === 'volume-1').volume.colorScale - await button('Duplicate Rep').click() - await edit(hex(2), '#ff00ff') - await page.locator('.rep-select').nth(1).click() - assert.equal(await hex(2).inputValue(), '#00ff00') - const saved = await save('custom-scales') - assert.deepEqual(saved.representations.items.find(rep => rep.id === 'volume-1').volume.colorScale, originalScale) - assert.equal(saved.representations.items.at(-1).volume.colorScale.stops[1].color, '#ff00ff') - await select('Color scale').selectOption('interpolatePlasma') - await page.locator('input[type="file"][accept="application/json,.json"]').setInputFiles(path.join(artifacts, 'custom-scales.json')) - await page.waitForFunction(() => document.querySelectorAll('.scale-stop').length === 3) - assert.equal(await select('Color scale').inputValue(), 'custom') - assert.equal(await position(2).inputValue(), '20') - assert.equal(await hex(2).inputValue(), '#00ff00') - const restored = await save('restored-scales') - assert.deepEqual(restored.representations, saved.representations) - record('Duplicated Reps own independent color scales; save/import preserves all stops, ranges and selection') - - for (let count = 3; count < 32; count++) await button('Add color stop').click() - assert.equal(await button('Add color stop').isDisabled(), true) - for (let count = 32; count > 2; count--) await button(`Remove color stop ${count}`).click() - assert.equal(await button('Remove color stop 1').isDisabled(), true) - assert.equal(await button('Remove color stop 2').isDisabled(), true) - await page.locator('input[type="file"][accept="application/json,.json"]').setInputFiles(path.join(artifacts, 'custom-scales.json')) - await page.waitForFunction(() => document.querySelectorAll('.scale-stop').length === 3) - await button('切换到中文').click() - assert.equal(await select('色彩轴').inputValue(), 'custom') - assert.equal(await input('色标点 2 的位置(%)').inputValue(), '20') - await page.locator('.color-scale-editor').scrollIntoViewIfNeeded() - await page.screenshot({ path: path.join(artifacts, 'color-scale-zh.png'), animations: 'disabled' }) - await page.setViewportSize({ width: 600, height: 850 }) - await page.waitForFunction(() => !document.querySelector('.rep-inspector')) - await button('打开表示层').click() - await page.locator('.color-scale-editor').scrollIntoViewIfNeeded() - assert.equal(await page.locator('.color-scale-editor').evaluate(el => el.scrollWidth <= el.clientWidth + 1), true) - await page.screenshot({ path: path.join(artifacts, 'color-scale-narrow.png'), animations: 'disabled' }) - record('2–32 stop bounds, Chinese/English controls and the 600 px layout work') - - // Restore an old automatic map against a one-sided field. All changes are - // confined to this browser's response; the shared preview data stays intact. - await page.route('**/session/esp.cub', async route => { - const response = await route.fetch(), lines = (await response.text()).trimEnd().split(/\r?\n/) - const header = 6 + Math.abs(Number(lines[2].trim().split(/\s+/)[0])) - const values = lines.slice(header).join(' ').trim().split(/\s+/).map(value => Math.abs(Number(value.replace(/[dD]/g, 'e'))) + 0.1) - await route.fulfill({ response, body: `${lines.slice(0, header).join('\n')}\n${values.join('\n')}\n` }) - }) - await page.setViewportSize({ width: 1280, height: 900 }) - await page.reload({ waitUntil: 'networkidle', timeout: 180000 }) - await page.locator('.rep-row').first().waitFor() - if (await button('Switch to English').count()) await button('Switch to English').click() - const legacy = structuredClone(original), oldVolume = legacy.representations.items.find(rep => rep.id === 'volume-1').volume - delete oldVolume.colorScale; delete oldVolume.color_stops; delete oldVolume.color_range - oldVolume.colormap = 'interpolateTransFlag' - const legacyFile = path.join(artifacts, 'legacy-auto-scale.json') - await writeFile(legacyFile, JSON.stringify(legacy)) - await page.locator('input[type="file"][accept="application/json,.json"]').setInputFiles(legacyFile) - await page.waitForFunction(() => document.querySelectorAll('.scale-stop').length === 2) - assert.equal(await select('Color scale').inputValue(), 'custom') - assert.ok(Number.parseFloat(await page.locator('.esp-legend footer').innerText()) > 0, 'the actual fitted range is strictly positive') - assert.equal(await hex(2).inputValue(), '#5bcefa') - const channels = (await hex(1).inputValue()).slice(1).match(/../g).map(channel => Number.parseInt(channel, 16)) - assert.ok(channels[0] < channels[1] && channels[1] < channels[2], 'positive fields retain the white-to-blue side of the legacy map') - const migratedState = await save('legacy-auto-migrated') - assert.equal(migratedState.representations.items.find(rep => rep.id === 'volume-1').volume.colorScale.stops.length, 2) - await select('Color scale').selectOption('interpolateTransFlag'); await select('Color scale').selectOption('custom') - assert.equal(await page.locator('.scale-stop').count(), 3) - assert.equal(await hex(2).inputValue(), '#ffffff'); assert.equal(await position(2).inputValue(), '50') - record('Legacy automatic one-sided ranges migrate after actual surface sampling; explicit new presets still use their chosen percentages') - assert.deepEqual(errors, []) - await writeFile(path.join(artifacts, 'verification.json'), JSON.stringify({ preview, checks, before, changed, actualRange, errors }, null, 2)) -} catch (error) { - await page.screenshot({ path: path.join(artifacts, 'failure.png'), animations: 'disabled' }).catch(() => {}) - console.error({ checks, errors }); throw error -} finally { await browser.close() } diff --git a/frontend/matterviz-viewer/tests/browser/frequency.mjs b/frontend/matterviz-viewer/tests/browser/frequency.mjs index 9419b11f..6fdab778 100644 --- a/frontend/matterviz-viewer/tests/browser/frequency.mjs +++ b/frontend/matterviz-viewer/tests/browser/frequency.mjs @@ -19,12 +19,12 @@ try { browser = await chromium.launch({ executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE, headless: true, - args: ['--no-sandbox', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'], + args: ['--enable-features=Vulkan', '--use-angle=vulkan', '--use-vulkan=swiftshader', '--enable-unsafe-webgpu', '--enable-unsafe-swiftshader'], }) page = await browser.newPage({ viewport: { width: 1280, height: 900 }, locale: 'en-US' }) page.on('pageerror', error => errors.push(error.message)) // Only the unrelated workflow catalog is stubbed. File input, mode adapter, - // MatterViz component, WebGL renderer and interactions are the production build. + // MatterViz component, renderer and interactions are the production build. await page.route('**/api/workflows/**', route => { assert.equal(route.request().method(), 'GET', 'viewing frequencies must not run a calculation') return route.fulfill({ contentType: 'application/json', body: JSON.stringify({ @@ -41,17 +41,21 @@ try { await file.setInputFiles(fixture('gaussian16-water')) const canvas = dialog.locator('canvas') await canvas.waitFor() - const step = dialog.getByRole('spinbutton', { name: 'Step input', exact: true }) + const step = dialog.getByRole('spinbutton', { name: 'step input', exact: true }) await page.waitForTimeout(1200) - assert.equal(await step.inputValue(), '0') + assert.equal(await step.inputValue(), '1') assert.equal(await dialog.getByRole('combobox', { name: 'Normal mode', exact: true }).locator('option').count(), 3) assert.match(await dialog.innerText(), /IR: 7.25 km\/mol/) assert.equal(await canvas.count(), 1) await page.evaluate(() => { window.frequencyCanvas = document.querySelector('dialog canvas') }) // Read MatterViz's public scene registry from the shared production chunk. // Rollup renames exports; locate the registry by the canvas key, not its minified name. - const chunks = (await readdir(new URL('../../dist/assets/', import.meta.url))) - .filter(name => name.endsWith('.js') && name.startsWith('structure-')) + const assets = new URL('../../dist/assets/', import.meta.url) + const chunks = [] + for (const map of (await readdir(assets)).filter(name => name.endsWith('.js.map'))) { + const { sources } = JSON.parse(await readFile(new URL(map, assets), 'utf8')) + if (sources.some(path => path.endsWith('/matterviz/dist/io/export.js'))) chunks.push(map.slice(0, -4)) + } assert.equal(chunks.length, 1) await page.evaluate(async chunk => { const module = await import(`/assets/${chunk}`) @@ -69,11 +73,8 @@ try { const geometryPositions = () => page.evaluate(() => { const positions = [] window.frequencyScenes.get(window.frequencyCanvas).scene.traverse(object => { - if (object.isInstancedMesh) { - for (let index = 0; index < object.count; index++) { - positions.push(...object.instanceMatrix.array.slice(index * 16 + 12, index * 16 + 15)) - } - } else if (object.isMesh) positions.push(...object.matrixWorld.elements.slice(12, 15)) + const atoms = object.geometry?.getAttribute('atomPositionRadius') + if (atoms) for (let i = 0; i < object.count; i++) positions.push(atoms.getX(i), atoms.getY(i), atoms.getZ(i)) }) return positions }) @@ -92,16 +93,16 @@ try { const play = dialog.locator('.play-button') await play.click() - await page.waitForFunction(() => Number(document.querySelector('[aria-label="Step input"]').value) > 0) + await page.waitForFunction(() => Number(document.querySelector('[aria-label="step input"]').value) > 1) await play.click() const paused = await step.inputValue() await page.waitForTimeout(250) assert.equal(await step.inputValue(), paused) - await step.fill('0') + await step.fill('1') await page.waitForTimeout(250) const equilibrium = await canvas.screenshot() const equilibriumPositions = await geometryPositions() - await step.fill('12') + await step.fill('13') await page.waitForTimeout(250) assert.notDeepEqual(await canvas.screenshot(), equilibrium, 'quarter-cycle must change rendered atoms') assert.notDeepEqual(await geometryPositions(), equilibriumPositions, 'the native scene must update geometry, not only pixel effects') @@ -111,7 +112,7 @@ try { const modePositions = await geometryPositions() await modes.selectOption('1') await waitForGeometryChange(modePositions, 'changing modes must update rendered geometry') - assert.equal(await step.inputValue(), '12', 'changing modes preserves the current visual phase') + assert.equal(await step.inputValue(), '13', 'changing modes preserves the current visual phase') const amplitude = dialog.getByRole('spinbutton', { name: 'Visual amplitude (Å)', exact: true }) for (const value of ['', '0', '-1', '10']) { await amplitude.fill(value) @@ -125,6 +126,10 @@ try { await waitForGeometryChange(amplitudePositions, 'changing amplitude must update rendered geometry') record('Mode selection and amplitude changes use the same canvas; invalid amplitude recovers') + // Capture upstream's reset pose for this mode and phase. + await canvas.dblclick({ position: { x: 15, y: 15 } }) + await page.waitForTimeout(300) + const homeCamera = await cameraPose() const bounds = await canvas.boundingBox() await page.mouse.move(bounds.x + bounds.width * .6, bounds.y + bounds.height * .5) await page.mouse.down() @@ -163,18 +168,21 @@ try { await canvas.screenshot({ path: `${artifacts}/camera-after.png` }) assert.ok(near(returned, rotated), `switching modes must preserve the camera: ${JSON.stringify({ rotated, returned })}`) await play.click() - await page.waitForFunction(() => Number(document.querySelector('[aria-label="Step input"]').value) !== 12) + await page.waitForFunction(() => Number(document.querySelector('[aria-label="step input"]').value) !== 13) await play.click() - assert.ok(near(await settledCamera(), rotated), 'playback must also preserve the native camera') - await step.fill('12') + // Upstream follows the frame center during playback. Rotation and zoom stay fixed. + assert.ok(near((await settledCamera()).slice(3), rotated.slice(3)), 'playback preserves camera orientation and zoom') + await step.fill('13') await page.waitForTimeout(250) assert.equal(await page.evaluate(() => document.querySelector('dialog canvas') === window.frequencyCanvas), true) - await dialog.getByRole('button', { name: 'Reset camera (or double-click)', exact: true }).click() - assert.ok(near(await settledCamera(), initialCamera), 'native reset must retain the initial camera baseline across frames') + await canvas.dblclick({ position: { x: 15, y: 15 } }) + const reset = await settledCamera() + assert.ok(near(reset.slice(3, 7), homeCamera.slice(3, 7)) && !near(reset, rotated), + `native reset restores the home orientation: ${JSON.stringify({ homeCamera, reset, rotated })}`) record('Native rotate/zoom and mode switching preserve the camera and canvas') await file.setInputFiles({ name: 'broken.cjson', mimeType: 'application/json', buffer: Buffer.from('{"chemical json":0}') }) - await dialog.getByRole('alert').waitFor() + await dialog.locator('.error[role="alert"]').waitFor() assert.equal(await modes.locator('option').count(), 3) assert.match(await dialog.locator('.filename').innerText(), /gaussian16-water/) await play.click() @@ -184,10 +192,10 @@ try { await file.setInputFiles({ name: 'imaginary.cjson', mimeType: 'application/json', buffer: Buffer.from(JSON.stringify(imaginary)) }) await page.waitForFunction(() => document.querySelector('dialog .filename')?.textContent === 'imaginary.cjson') assert.match(await modes.locator('option').first().textContent(), /-2169.76 cm⁻¹ \(imaginary\)/) - assert.equal(await step.inputValue(), '0') + assert.equal(await step.inputValue(), '1') await page.waitForTimeout(250) - assert.equal(await step.inputValue(), '0', 'a replacement file must stop existing playback') - assert.equal(await dialog.getByRole('alert').count(), 0) + assert.equal(await step.inputValue(), '1', 'a replacement file must stop existing playback') + assert.equal(await dialog.locator('.error').count(), 0) record('Invalid file keeps valid data; replacement resets playback and preserves negative frequency') await file.setInputFiles(fixture('orca42-dvb')) @@ -196,7 +204,7 @@ try { assert.equal(await modes.locator('option').count(), 54) assert.match(await modes.locator('option').first().textContent(), /45.75/) await modes.selectOption('53') - await step.fill('12') + await step.fill('13') await page.waitForTimeout(250) await page.screenshot({ path: `${artifacts}/orca-frequency.png` }) await page.setViewportSize({ width: 600, height: 800 }) @@ -206,7 +214,7 @@ try { record('Real ORCA export: all 54 modes and responsive viewer') await page.evaluate(() => { window.frequencyClosingCanvas = document.querySelector('dialog canvas') }) - await page.keyboard.press('Escape') + await dialog.getByRole('button', { name: 'Close vibration viewer', exact: true }).click() await dialog.waitFor({ state: 'hidden' }) assert.equal(await open.evaluate(element => document.activeElement === element), true) assert.equal(await page.locator('canvas').count(), 0) @@ -217,7 +225,7 @@ try { await open.click() await file.setInputFiles(fixture('gaussian16-water')) await canvas.waitFor() - assert.equal(await step.inputValue(), '0') + assert.equal(await step.inputValue(), '1') assert.equal(await canvas.count(), 1) await page.screenshot({ path: `${artifacts}/gaussian-frequency.png` }) record('Closing restores workbench focus and releases the scene; reopening starts paused') diff --git a/frontend/matterviz-viewer/tests/browser/rep-color.mjs b/frontend/matterviz-viewer/tests/browser/rep-color.mjs deleted file mode 100644 index e4a26b2f..00000000 --- a/frontend/matterviz-viewer/tests/browser/rep-color.mjs +++ /dev/null @@ -1,121 +0,0 @@ -// Real WebGL pixels: brightness gain, saturation, unchanged alpha and saved settings. -import assert from 'node:assert/strict' -import { mkdir, readFile, writeFile } from 'node:fs/promises' -import path from 'node:path' -const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright') -const preview = process.env.PREVIEW_URL || 'http://127.0.0.1:5297/?manifest=/session/surface-manifest.json' -const artifacts = process.env.ARTIFACT_DIR || '/tmp/multiwfn-rep-color' -await mkdir(artifacts, { recursive: true }) -const browser = await chromium.launch({ executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE, - headless: true, args: ['--no-sandbox', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'] }) -const page = await browser.newPage({ viewport: { width: 1200, height: 800 }, locale: 'en-US', acceptDownloads: true }) -const errors = [], checks = [], results = {} -page.on('pageerror', error => errors.push(String(error))) -page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()) }) -const button = name => page.getByRole('button', { name, exact: true }) -const input = name => page.getByRole('spinbutton', { name, exact: true }) -const tab = name => page.getByRole('tab', { name, exact: true }) -const select = name => page.getByRole('combobox', { name, exact: true }) -const record = message => { checks.push(message); console.log('PASS', message) } -const sample = async name => { - await page.waitForTimeout(250) - const result = await page.evaluate(() => { - const { scene, camera } = window.colorScene, renderer = window.colorRenderer - renderer.render(scene, camera) - const canvas = document.createElement('canvas'), source = renderer.domElement - canvas.width = source.width; canvas.height = source.height - const context = canvas.getContext('2d'); context.drawImage(source, 0, 0) - const data = context.getImageData(0, 0, canvas.width, canvas.height).data - let weight = 0, chroma = 0, brightness = 0, alphaHash = 2166136261, colorHash = 2166136261 - for (let i = 0; i < data.length; i += 4) { - const [r, g, b, a] = data.subarray(i, i + 4) - alphaHash = Math.imul(alphaHash ^ a, 16777619) - for (let c = 0; c < 4; c++) colorHash = Math.imul(colorHash ^ data[i + c], 16777619) - if (a < 16) continue - weight += a; chroma += (Math.max(r, g, b) - Math.min(r, g, b)) * a - brightness += (0.2126 * r + 0.7152 * g + 0.0722 * b) * a - } - return { chroma: chroma / weight, brightness: brightness / weight, weight, alphaHash, colorHash, - camera: [camera.position.toArray(), camera.quaternion.toArray(), camera.zoom], png: canvas.toDataURL('image/png') } - }) - if (name) await writeFile(path.join(artifacts, `${name}.png`), Buffer.from(result.png.split(',')[1], 'base64')) - delete result.png - assert.ok(result.weight > 100000, 'capture contains visible geometry') - return result -} -const colors = async name => { - await input('Saturation').fill('1'); const normal = await sample(`${name}-1`) - await input('Saturation').fill('0'); const gray = await sample() - await input('Saturation').fill('3'); const vivid = await sample(`${name}-3`) - assert.ok(gray.chroma < 1, `${name}: saturation 0 must be grayscale (${gray.chroma})`) - assert.ok(vivid.chroma > normal.chroma * 1.05, `${name}: 3 must be more saturated than 1 (${vivid.chroma} vs ${normal.chroma})`) - assert.equal(gray.alphaHash, normal.alphaHash); assert.equal(vivid.alphaHash, normal.alphaHash) - assert.deepEqual(vivid.camera, normal.camera) - await input('Saturation').fill('1') - assert.equal((await sample()).colorHash, normal.colorHash, 'returning to 1 exactly restores the original pixels') - results[name] = { normal, gray, vivid } -} -try { - await page.goto(preview, { waitUntil: 'networkidle', timeout: 180000 }) - await page.locator('.rep-row').first().waitFor() - await page.evaluate(async () => { - const url = performance.getEntriesByType('resource').map(e => e.name).find(url => /\/matterviz\.js/.test(url)) - const mv = await import(url), canvas = document.querySelector('.structure canvas') - window.colorScene = mv.scene_registry.get(canvas); window.colorRenderer = mv.renderer_registry.get(canvas) - }) - await page.waitForFunction(() => window.colorScene.scene.getObjectByName('rep-copies-volume-1')?.children[0]?.children.length > 0) - await button('Scene').click(); await page.getByRole('checkbox', { name: 'Axes', exact: true }).uncheck() - await button('Representations').click() - await page.locator('.rep-visibility').nth(1).click() - await tab('Appearance').click() - assert.equal(await input('Diffuse reflection').getAttribute('max'), '3') - assert.equal(await input('Saturation').getAttribute('max'), '3') - for (const model of ['matte', 'glossy', 'pbr', 'unlit']) { - await select('Shading model').selectOption(model) - await colors(`molecule-${model}`) - if (model === 'unlit') assert.equal(await input('Diffuse reflection').count(), 0) - else { - await input('Diffuse reflection').fill('3'); const bright = await sample() - assert.ok(bright.brightness > results[`molecule-${model}`].normal.brightness + 3, `${model}: diffuse gain must brighten the model`) - await input('Diffuse reflection').fill('1') - } - } - record('All four material models: grayscale at 0, stronger color at 3, exact reset at 1; diffuse 3 brightens lit materials') - await tab('Data & drawing').click(); await button('Stick').click(); await tab('Appearance').click() - await colors('bonds') - record('Bond gradients support saturation without changing alpha or camera') - await select('Shading model').selectOption('glossy') - await input('Diffuse reflection').fill('2.4'); await input('Saturation').fill('1.6') - await page.locator('.rep-visibility').first().click(); await page.locator('.rep-visibility').nth(1).click() - await page.locator('.rep-select').nth(1).click() - await page.waitForFunction(() => window.colorScene.scene.getObjectByName('rep-copies-volume-1')?.children[0]?.children.length > 0) - await input('Opacity').fill('0.65') - await colors('surface') - await tab('Data & drawing').click(); await select('Drawing method').selectOption('wire'); await tab('Appearance').click() - await colors('wireframe') - await tab('Data & drawing').click(); await select('Drawing method').selectOption('surface'); await tab('Appearance').click() - record('Mapped surface and wireframe saturation works, including unchanged translucent alpha') - await input('Diffuse reflection').fill('2.3'); await input('Saturation').fill('2.6') - assert.equal(await select('Material preset').inputValue(), 'custom') - await button('Save').click() - const download = page.waitForEvent('download'); await button('Save display settings').click() - const file = path.join(artifacts, 'colors.json'); await (await download).saveAs(file) - const saved = JSON.parse(await readFile(file, 'utf8')) - assert.equal(saved.representations.items[0].material.saturation, 1.6) - assert.equal(saved.representations.items[0].material.diffuse, 2.4) - assert.equal(saved.representations.items[1].material.saturation, 2.6) - assert.equal(saved.representations.items[1].material.diffuse, 2.3) - await input('Saturation').fill('0.2'); await input('Diffuse reflection').fill('0.2') - await page.locator('input[type="file"][accept="application/json,.json"]').setInputFiles(file) - await page.waitForFunction(() => [...document.querySelectorAll('.rep-scalar')].find(row => row.firstElementChild?.textContent === 'Saturation')?.querySelector('input[type=number]')?.value === '2.6') - assert.equal(await input('Diffuse reflection').inputValue(), '2.3') - await button('切换到中文').click() - assert.equal(await input('饱和度').inputValue(), '2.6'); assert.equal(await input('漫反射').inputValue(), '2.3') - await page.screenshot({ path: path.join(artifacts, 'controls-zh.png'), animations: 'disabled' }) - record('Independent values above 1 round-trip through settings; bilingual labels and custom preset detection work') - assert.deepEqual(errors, []) - await writeFile(path.join(artifacts, 'verification.json'), JSON.stringify({ preview, checks, results, errors }, null, 2)) -} catch (error) { - await page.screenshot({ path: path.join(artifacts, 'failure.png'), animations: 'disabled' }).catch(() => {}) - console.error({ checks, results, errors }); throw error -} finally { await browser.close() } diff --git a/frontend/matterviz-viewer/tests/browser/representations.mjs b/frontend/matterviz-viewer/tests/browser/representations.mjs deleted file mode 100644 index bfd84777..00000000 --- a/frontend/matterviz-viewer/tests/browser/representations.mjs +++ /dev/null @@ -1,255 +0,0 @@ -// Real WebGL acceptance. Run against the molecule/density/ESP preview (README). -import assert from 'node:assert/strict' -import { mkdir, readFile, writeFile } from 'node:fs/promises' -import path from 'node:path' -const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright') -const preview = process.env.PREVIEW_URL || 'http://127.0.0.1:5297/?manifest=/session/surface-manifest.json' -const artifacts = process.env.ARTIFACT_DIR || '/tmp/multiwfn-representations' -await mkdir(artifacts, { recursive: true }) -const browser = await chromium.launch({ executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE, headless: true, - args: ['--no-sandbox', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'] }) -const page = await browser.newPage({ viewport: { width: 1440, height: 960 }, locale: 'en-US', acceptDownloads: true }) -const errors = [], checks = [] -page.on('pageerror', error => errors.push(String(error))) -page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()) }) -page.setDefaultTimeout(20000) -const record = message => { checks.push(message); console.log('PASS', message) } -const button = name => page.getByRole('button', { name, exact: true }) -const tab = name => page.getByRole('tab', { name, exact: true }) -const input = name => page.getByRole('spinbutton', { name, exact: true }) -const select = name => page.getByRole('combobox', { name, exact: true }) -const settle = () => page.waitForTimeout(300) -const rename = async name => { await page.getByRole('textbox', { name: 'Rep name', exact: true }).fill(name); await tab('Data & drawing').click() } -const save = async (name, zh = false) => { - await button(zh ? '保存' : 'Save').click() - const event = page.waitForEvent('download') - await button(zh ? '保存显示设置' : 'Save display settings').click() - const file = path.join(artifacts, `${name}.json`) - await (await event).saveAs(file) - await page.getByRole('dialog', { name: zh ? '保存选项' : 'Save controls', exact: true }).waitFor({ state: 'hidden' }) - return JSON.parse(await readFile(file, 'utf8')) -} -const scene = async () => page.evaluate(() => { - const { scene, camera } = window.repTestScene - const reps = [] - let cameras = 0, lights = 0 - scene.traverse(object => { - cameras += Boolean(object.isCamera); lights += Boolean(object.isLight) - if (!object.name.startsWith('representation-')) return - const meshes = [] - object.traverseVisible(mesh => { - if (!mesh.isMesh || (Array.isArray(mesh.material) ? mesh.material : [mesh.material]).every(m => !m.visible)) return - const material = Array.isArray(mesh.material) ? mesh.material[0] : mesh.material - meshes.push({ geometry: mesh.geometry.uuid, material: material.uuid, type: material.type, opacity: material.opacity, - roughness: material.roughness, metalness: material.metalness, planes: material.clippingPlanes?.length ?? 0, - shape: mesh.geometry.type, count: mesh.count, position: mesh.position.toArray() }) - }) - const copies = object.getObjectByName(object.name.replace('representation-', 'rep-copies-')) - reps.push({ id: object.name.replace('representation-', ''), meshes, order: object.renderOrder, - copies: copies?.children.map(copy => copy.position.toArray()) }) - }) - return { reps, cameras, lights, position: camera.position.toArray(), canvasCount: document.querySelectorAll('canvas').length } -}) -try { - await page.goto(preview, { waitUntil: 'networkidle', timeout: 180000 }) - await page.locator('.rep-row').first().waitFor() - await page.evaluate(async () => { - const url = performance.getEntriesByType('resource').map(e => e.name).find(url => /\/matterviz\.js/.test(url)) - const mv = await import(url) - window.repTestScene = mv.scene_registry.get(document.querySelector('canvas')) - window.repTestCanvas = document.querySelector('canvas') - }) - await page.waitForFunction(() => { - const group = window.repTestScene.scene.getObjectByName('rep-copies-volume-1') - return group?.children.length > 0 && group.children[0].children.length > 0 - }) - let initial = await scene() - assert.equal(initial.canvasCount, 1); assert.equal(initial.cameras, 1); assert.equal(initial.lights, 4) - assert.equal(initial.reps.length, 2) - assert.ok(initial.reps.find(rep => rep.id === 'volume-1').meshes.length) - await page.screenshot({ path: path.join(artifacts, 'reps-initial.png') }) - record('Structure and real density volume overlay in one canvas with one camera and four lights') - - await button('Add Rep').click() - await select('Source type').selectOption('volume'); await select('Dataset').selectOption('0') - await input('Isovalue').fill('0.002'); await settle() - assert.equal(await page.locator('.rep-row').count(), 4) - assert.equal((await scene()).reps.length, 3) - await button('Delete Rep').click(); await page.locator('.rep-select').first().click() - record('Create a Rep, choose its data type/dataset/drawing value, then delete it without changing existing Reps') - - await button('Duplicate Rep').click(); await rename('Independent molecule') - await button('Spacefill').click() - await tab('Appearance').click() - assert.equal(await page.locator('[role=tabpanel]:visible').count(), 1) - await input('Opacity').fill('0.4') - await input('Diffuse reflection').fill('0.25') - await input('Highlight strength').fill('0.7') - await select('Shading model').selectOption('pbr') - await input('Roughness').fill('0.2'); await input('Metalness').fill('0.8') - await settle() - let current = await scene() - assert.deepEqual(current.position, initial.position) - assert.equal(current.cameras, 1); assert.equal(current.lights, 4) - const duplicate = current.reps.find(rep => !['structure-1', 'volume-1'].includes(rep.id)) - assert.ok(duplicate.meshes.some(mesh => mesh.type === 'MeshStandardMaterial' && mesh.opacity === .4 && mesh.roughness === .2 && mesh.metalness === .8)) - assert.ok(current.reps.find(rep => rep.id === 'structure-1').meshes.some(mesh => mesh.type === 'MeshPhongMaterial' && mesh.opacity === 1)) - await tab('Data & drawing').click(); await button('Ball+Stick').click(); await settle() - current = await scene() - assert.ok(current.reps.find(rep => rep.id === duplicate.id).meshes.some(mesh => mesh.shape === 'CylinderGeometry' && mesh.type === 'MeshStandardMaterial' && mesh.metalness === .8), 'bonds use the same PBR model') - await tab('Appearance').click(); await select('Material preset').selectOption('glass1'); await settle() - assert.equal(await input('Opacity').inputValue(), '0.35') - await button('Move Rep up').click(); await button('Move Rep down').click() - await button('Hide Independent molecule').click(); await settle() - assert.equal((await scene()).reps.length, 2) - record('Independent drawing/materials, real PBR atoms and bonds, glass opacity, ordering and visibility') - - await page.locator('.rep-select').nth(1).click() - await tab('Data & drawing').click() - await select('Color by').selectOption('1') - await page.getByRole('checkbox', { name: 'Manual color range', exact: true }).check() - await input('Minimum').fill('-0.04'); await input('Maximum').fill('0.06') - await tab('PBC').click() - await page.getByRole('checkbox', { name: 'Repeat this Rep periodically', exact: true }).check() - await page.getByRole('checkbox', { name: 'Use custom lattice vectors', exact: true }).check() - const cell = [[14, 2, 0], [0, 14, 0], [0, 0, 14]] - for (let row = 0; row < 3; row++) for (let col = 0; col < 3; col++) await input(`Lattice ${'abc'[row]} ${'xyz'[col]}`).fill(String(cell[row][col])) - await page.getByRole('checkbox', { name: 'Repeat along b', exact: true }).uncheck() - await page.getByRole('checkbox', { name: 'Repeat along c', exact: true }).uncheck() - await input('a lower bound').fill('-0.5'); await input('a upper bound').fill('1.5') - await button('Apply periodic display').click(); await settle() - let volume = (await scene()).reps.find(rep => rep.id === 'volume-1') - assert.deepEqual(volume.copies, [[-14, -2, 0], [0, 0, 0], [14, 2, 0]]) - assert.ok(volume.meshes.every(mesh => mesh.planes === 2)) - assert.ok(new Set(volume.meshes.map(mesh => mesh.geometry)).size < volume.meshes.length, 'volume copies share extracted geometry') - assert.ok(new Set(volume.meshes.map(mesh => mesh.material)).size < volume.meshes.length, 'volume copies share materials') - await input('Lattice a x').fill('0'); await input('Lattice a y').fill('0') - await button('Apply periodic display').click() - assert.match(await page.getByRole('alert').innerText(), /nonsingular/) - assert.deepEqual((await scene()).reps.find(rep => rep.id === 'volume-1').copies, volume.copies) - await input('Lattice a x').fill('14'); await input('Lattice a y').fill('2'); await button('Apply periodic display').click() - record('Fractional negative PBC with custom skew vectors, actual clipping, shared geometry, invalid-cell rejection') - - await page.locator('.rep-select').last().click() - await page.getByRole('checkbox', { name: 'Repeat this Rep periodically', exact: true }).check() - await page.getByRole('checkbox', { name: 'Use custom lattice vectors', exact: true }).check() - for (let row = 0; row < 3; row++) for (let col = 0; col < 3; col++) await input(`Lattice ${'abc'[row]} ${'xyz'[col]}`).fill(String(cell[row][col])) - await page.getByRole('checkbox', { name: 'Repeat along b', exact: true }).uncheck() - await page.getByRole('checkbox', { name: 'Repeat along c', exact: true }).uncheck() - await input('a lower bound').fill('-0.25'); await input('a upper bound').fill('1.25') - await button('Apply periodic display').click(); await button('Show Independent molecule').click(); await settle() - const repeated = (await scene()).reps.find(rep => rep.id === duplicate.id) - assert.ok(repeated.meshes.some(mesh => mesh.shape === 'SphereGeometry' && mesh.count > 32 && mesh.planes === 2)) - assert.ok((await scene()).reps.find(rep => rep.id === 'structure-1').meshes.every(mesh => mesh.planes === 0)) - assert.deepEqual((await scene()).reps.find(rep => rep.id === 'volume-1').copies, volume.copies) - await button('Hide Independent molecule').click() - await page.locator('.rep-select').nth(1).click() - record('Structure PBC independently replicates and clips atoms/bonds alongside the volume Rep') - - const saved = await save('representations') - assert.equal(saved.representations.items.length, 4) - const storedVolume = saved.representations.items.find(rep => rep.id === 'volume-1') - assert.deepEqual(storedVolume.periodic.cell, cell); assert.equal(storedVolume.volume.color_volume_idx, 1) - await button('Delete Rep').click() - assert.equal(await page.locator('.rep-row').count(), 3) - await page.locator('input[accept="application/json,.json"]').setInputFiles(path.join(artifacts, 'representations.json')) - await page.waitForFunction(() => document.querySelectorAll('.rep-row').length === 4) - const restored = await save('restored') - assert.deepEqual(restored.representations, saved.representations) - await button('切换到中文').click() - await page.getByRole('complementary', { name: '表示层编辑器', exact: true }).waitFor() - assert.equal(await page.locator('html').getAttribute('lang'), 'zh-CN') - const chinese = await save('chinese', true) - assert.deepEqual(chinese, restored, 'language switch preserves camera, data and all display settings') - assert.equal(await page.evaluate(() => document.querySelector('canvas') === window.repTestCanvas), true) - await page.screenshot({ path: path.join(artifacts, 'reps-chinese.png') }) - await button('Switch to English').click() - record('Save/restore all independent Reps and color sources; bilingual switch preserves complete state and canvas') - - // Use source atom coordinates from the real cube and the existing scene camera. - await button('Hide Density').click() - await page.locator('.rep-select').first().click(); await tab('Data & drawing').click() - await page.getByRole('textbox', { name: 'Atom selection', exact: true }).fill('index 1-2') - await page.getByRole('textbox', { name: 'Rep name', exact: true }).click() - await button('Scene').click(); await button('Fit all visible Reps').click(); await settle() - const points = await page.evaluate(() => { - const { scene, camera } = window.repTestScene, group = scene.getObjectByName('representation-structure-1') - const points = [] - group.traverseVisible(mesh => { - if (!mesh.isInstancedMesh || mesh.geometry.type !== 'SphereGeometry' || mesh.material.opacity === 0 || !mesh.material.visible) return - for (let index = 0; index < mesh.count; index++) { - const matrix = mesh.matrix.clone(); mesh.getMatrixAt(index, matrix) - const world = mesh.position.clone().setFromMatrixPosition(matrix).applyMatrix4(mesh.matrixWorld) - const p = world.clone().project(camera) - const bounds = document.querySelector('canvas').getBoundingClientRect() - points.push({ world: world.toArray(), x: bounds.x + (p.x + 1) * bounds.width / 2, y: bounds.y + (1 - p.y) * bounds.height / 2 }) - } - }) - return points - }) - assert.equal(points.length, 2) - await page.mouse.click(points[0].x, points[0].y); await page.locator('.measurement-result').waitFor() - await page.mouse.click(points[1].x, points[1].y) - await page.waitForFunction(() => document.querySelector('.measurement-result strong')?.textContent.includes('Å')) - assert.match(await page.locator('.measurement-result').innerText(), /1.*2|2.*1/) - await button('Clear measurement').click() - await page.locator('.measurement-result').waitFor({ state: 'hidden' }) - await page.mouse.click(points[0].x, points[0].y); await page.locator('.measurement-result').waitFor() - await page.mouse.click(points[0].x, points[0].y); await page.locator('.measurement-result').waitFor({ state: 'hidden' }) - record('Real atom clicks measure source identities; clear and deselect-last remove measurement readout') - - for (const name of ['View', 'Tools', 'Save']) { - await button(name).focus(); await page.keyboard.press('Enter') - await page.getByRole('dialog', { name: `${name} controls`, exact: true }).waitFor() - await page.keyboard.press('Escape') - assert.equal(await button(name).evaluate(e => e === document.activeElement), true) - } - await button('Tools').click() - for (const name of ['ESP surface', 'AIM critical points and paths...', 'Quantitative surface results...']) assert.equal(await button(name).count(), 1) - await page.keyboard.press('Escape') - await button('View').click(); await button('2D Slice').click() - await page.getByRole('complementary', { name: '2D volume slice', exact: true }).waitFor() - await button('Close slice panel').click() - await button('Tools').click(); await button('Edit atoms and bonds...').click() - await page.locator('.rep-edit-banner').waitFor() - await button('Measure / Edit').click(); await button('Edit Bonds').click() - await page.getByRole('button', { name: 'Delete', exact: true }).click() - await settle() - const nativePoint = await page.evaluate(points => { - const { camera } = window.repTestScene, bounds = document.querySelector('canvas').getBoundingClientRect() - const world = camera.position.clone().fromArray(points[0].world).add(camera.position.clone().fromArray(points[1].world)).multiplyScalar(.5).project(camera) - return { x: bounds.x + (world.x + 1) * bounds.width / 2, y: bounds.y + (1 - world.y) * bounds.height / 2 } - }, points) - await page.mouse.click(nativePoint.x, nativePoint.y) - await page.waitForFunction(() => !document.querySelector('[aria-label="Undo bond edit (Cmd/Ctrl+Z)"]').disabled) - await button('Back to Reps').click(); await settle() - let edited = (await scene()).reps.find(rep => rep.id === 'structure-1') - assert.equal(edited.meshes.filter(mesh => mesh.shape === 'CylinderGeometry' && mesh.opacity > 0).length, 0, - 'deleting the source bond removes it from a Rep') - await button('Tools').click(); await button('Edit atoms and bonds...').click() - await button('Measure / Edit').click(); await button('Edit Bonds').click() - await button('Undo bond edit (Cmd/Ctrl+Z)').click() - await button('Back to Reps').click(); await settle() - edited = (await scene()).reps.find(rep => rep.id === 'structure-1') - assert.ok(edited.meshes.some(mesh => mesh.shape === 'CylinderGeometry' && mesh.opacity > 0), 'undo restores the bond in Reps') - record('Native bond deletion and undo propagate back to the independently selected structure Rep') - await tab('Data & drawing').focus(); await page.keyboard.press('ArrowRight') - assert.equal(await tab('Appearance').getAttribute('aria-selected'), 'true') - await input('Opacity').fill('0.9') - await page.setViewportSize({ width: 600, height: 820 }); await settle() - await button('Open representations').click() - await page.waitForFunction(() => Math.abs(document.querySelector('canvas').getBoundingClientRect().height - document.querySelector('.scene-viewport').getBoundingClientRect().height) < 1) - assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true) - const pane = await page.locator('.rep-editor').boundingBox(), canvas = await page.locator('canvas').boundingBox() - assert.ok(pane.height >= 100, `editor must remain usable, height ${pane.height}`) - assert.ok(canvas.height >= 180, `canvas must remain usable, height ${canvas.height}`) - await page.screenshot({ path: path.join(artifacts, 'reps-narrow.png') }) - await page.locator('.rep-inspector').getByRole('button', { name: 'Close inspector', exact: true }).click(); await settle() - await page.waitForFunction(height => document.querySelector('canvas').getBoundingClientRect().height > height, canvas.height) - record('Keyboard tabs/menus, analysis/slice/editing entry points, usable collapsible 600 px layout') - assert.deepEqual(errors, []) - await writeFile(path.join(artifacts, 'verification.json'), JSON.stringify({ preview, checks, errors }, null, 2)) -} catch (error) { - await page.screenshot({ path: path.join(artifacts, 'failure.png') }).catch(() => {}) - console.error({ checks, errors }); throw error -} finally { await browser.close() } diff --git a/frontend/matterviz-viewer/tests/browser/scene-export.mjs b/frontend/matterviz-viewer/tests/browser/scene-export.mjs index 31f930f7..22bde478 100644 --- a/frontend/matterviz-viewer/tests/browser/scene-export.mjs +++ b/frontend/matterviz-viewer/tests/browser/scene-export.mjs @@ -1,117 +1,108 @@ -// Pixel-level acceptance of actual scene downloads, including translucent Reps. -// Start preview:session first; Playwright is supplied by the developer environment. +// Exercise the production workbench, the upstream finish selector and the real PNG download. import assert from 'node:assert/strict' -import { mkdir, readFile, writeFile } from 'node:fs/promises' -import path from 'node:path' -const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright') -const preview = process.env.PREVIEW_URL || 'http://127.0.0.1:5297/?manifest=/session/surface-manifest.json' -const artifacts = process.env.ARTIFACT_DIR || '/tmp/multiwfn-scene-export' -await mkdir(artifacts, { recursive: true }) +import { readFile } from 'node:fs/promises' +import { chromium } from 'playwright' +import { preview } from 'vite' + +const server = process.env.PREVIEW_URL ? undefined : await preview({ preview: { port: 0, host: '127.0.0.1' } }) +const base = process.env.PREVIEW_URL ?? server.resolvedUrls.local[0] const browser = await chromium.launch({ executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE, - headless: true, args: ['--no-sandbox', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'] }) -const page = await browser.newPage({ viewport: { width: 1200, height: 800 }, locale: 'en-US', acceptDownloads: true }) -const errors = [], checks = [] -page.on('pageerror', error => errors.push(String(error))) -page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()) }) -const button = name => page.getByRole('button', { name, exact: true }) -const record = message => { checks.push(message); console.log('PASS', message) } -const state = () => page.evaluate(() => { - const { camera, scene } = window.exportTestScene - const canvas = document.querySelector('.structure canvas') - const materials = [] - scene.traverse(object => { - if (object.isMesh) for (const material of Array.isArray(object.material) ? object.material : [object.material]) { - materials.push([material.uuid, material.opacity, material.transparent]) - } - }) - return { position: camera.position.toArray(), rotation: camera.quaternion.toArray(), zoom: camera.zoom, - width: canvas.width, height: canvas.height, ratio: window.exportTestRenderer.getPixelRatio(), - background: getComputedStyle(canvas.closest('.structure')).getPropertyValue('--struct-bg-override'), - materials, sameCanvas: canvas === window.exportTestCanvas } -}) -const pixels = async file => page.evaluate(async data => { - const image = new Image() - image.src = `data:image/png;base64,${data}` - await image.decode() - const canvas = document.createElement('canvas') - canvas.width = image.width; canvas.height = image.height - const context = canvas.getContext('2d') - context.drawImage(image, 0, 0) - const rgba = context.getImageData(0, 0, canvas.width, canvas.height).data - const corner = Array.from(rgba.slice(0, 4)) - let transparent = 0, partial = 0, opaque = 0, foreground = 0 - for (let i = 0; i < rgba.length; i += 4) { - if (rgba[i + 3] === 0) transparent++ - else if (rgba[i + 3] === 255) opaque++ - else partial++ - if (rgba[i + 3] > 0 && (rgba[i] !== corner[0] || rgba[i + 1] !== corner[1] || rgba[i + 2] !== corner[2])) foreground++ + args: ['--enable-features=Vulkan', '--use-angle=vulkan', '--use-vulkan=swiftshader', '--enable-unsafe-webgpu', '--enable-unsafe-swiftshader'] }) +const finishes = ['satin', 'translucent_shell', 'chalk', 'unlit'] + +// A signed p-like orbital and two independent scalar fields on the same finite grid. +function cube(role) { + const axis = 23, data = [] + for (let i = 0; i < axis; i++) for (let j = 0; j < axis; j++) for (let k = 0; k < axis; k++) { + const [x, y, z] = [i, j, k].map(n => (n - 11) / 5) + const rho = Math.exp(-x*x - y*y - z*z) + data.push(role === 'potential' ? x : role === 'orbital' ? x*rho : rho) } - return { width: image.width, height: image.height, corner, transparent, partial, opaque, foreground } -}, (await readFile(file)).toString('base64')) -const save = async (name, transparent, zh = false) => { - const before = await state() - await button(zh ? '保存' : 'Save').click() - const checkbox = page.getByRole('checkbox', { name: zh ? '透明背景' : 'Transparent background', exact: true }) - if (transparent === undefined) assert.equal(await checkbox.isChecked(), false, 'opaque background is the default') - else await checkbox.setChecked(transparent) - const download = page.waitForEvent('download') - await button(zh ? 'PNG 图像' : 'PNG image').click() - const file = path.join(artifacts, `${name}.png`) - await (await download).saveAs(file) - await page.getByRole('dialog', { name: zh ? '保存选项' : 'Save controls', exact: true }).waitFor({ state: 'hidden' }) - await page.waitForFunction(() => !document.querySelector('.return')?.disabled) - assert.deepEqual(await state(), before, 'export preserves camera, background, materials and canvas size') - const stats = await pixels(file) - assert.ok(stats.foreground > 1000, 'download contains the rendered model') - return stats + return ['Multiwfn', role, '2 -2.2 -2.2 -2.2', '-23 0.2 0 0', '-23 0 0.2 0', '-23 0 0 0.2', + '6 0 -0.8 0 0', '8 0 0.8 0 0', data.join(' ')].join('\n') } -try { - await page.goto(preview, { waitUntil: 'networkidle', timeout: 180000 }) - await page.locator('.rep-row').first().waitFor() - await page.evaluate(async () => { - const url = performance.getEntriesByType('resource').map(e => e.name).find(url => /\/matterviz\.js/.test(url)) - const mv = await import(url) - const canvas = document.querySelector('.structure canvas') - window.exportTestScene = mv.scene_registry.get(canvas) - window.exportTestRenderer = mv.renderer_registry.get(canvas) - window.exportTestCanvas = canvas - }) - await page.waitForFunction(() => window.exportTestScene.scene.getObjectByName('rep-copies-volume-1')?.children[0]?.children.length > 0) - const white = await save('white') - assert.deepEqual(white.corner, [255, 255, 255, 255]) - assert.equal(white.transparent + white.partial, 0) - record('Default PNG has an opaque white background and visible structure/surface') - - const transparent = await save('transparent', true) - assert.equal(transparent.corner[3], 0) - assert.ok(transparent.transparent > 1000 && transparent.partial > 1000) - assert.equal(transparent.width, white.width); assert.equal(transparent.height, white.height) - record('Transparent PNG has empty alpha outside the model and partial alpha on translucent surfaces') - await button('Scene').click() - await page.getByLabel('Background', { exact: true }).fill('#64a0d0') - await page.getByRole('spinbutton', { name: 'Background opacity', exact: true }).fill('0.35') - const colored = await save('colored', false) - assert.deepEqual(colored.corner, [100, 160, 208, 255]) - assert.equal(colored.transparent + colored.partial, 0) - record('Opaque export uses the chosen background color even with translucent on-screen background') - - await button('切换到中文').click() - const chinese = await save('transparent-zh', true, true) - assert.equal(chinese.corner[3], 0) - await button('保存').click() - assert.equal(await page.getByRole('checkbox', { name: '透明背景', exact: true }).isChecked(), true) - await page.screenshot({ path: path.join(artifacts, 'save-menu-zh.png'), animations: 'disabled' }) - await page.keyboard.press('Escape') - await button('工具').click(); await button('编辑原子和键…').click() - await page.locator('.rep-edit-banner').waitFor() - await button('返回表示层').click() - assert.equal(await page.locator('.tool-rail').getByRole('button', { name: '编辑', exact: true }).count(), 0) - record('Chinese export option works, selection persists and source editing remains available in Tools') - assert.deepEqual(errors, []) - await writeFile(path.join(artifacts, 'verification.json'), JSON.stringify({ preview, checks, white, transparent, colored, chinese, errors }, null, 2)) -} catch (error) { - await page.screenshot({ path: path.join(artifacts, 'failure.png') }).catch(() => {}) - console.error({ checks, errors }) - throw error -} finally { await browser.close() } +try { + for (const [mode, width] of [['orbital', 1080], ['esp', 390]]) { + const page = await browser.newPage({ viewport: { width, height: 720 }, locale: 'en-US' }) + try { + const errors = [] + page.on('pageerror', error => errors.push(error.message)) + const entries = mode === 'orbital' + ? [{ path: 'orbital.cube', role: 'orbital', mode: 'signed', isovalue: .15, opacity: 1 }] + : [{ path: 'density.cube', name: 'Density', analysisKind: 'esp-density', isovalue: .15, + colorMapping: { path: 'potential.cube', range: [-1, 1], stops: [ + { position: 0, color: '#ff0000' }, { position: .5, color: '#ffffff' }, { position: 1, color: '#0000ff' }] } }, + { path: 'potential.cube', name: 'Potential', analysisKind: 'esp-potential', visible: false }] + const url = new URL((mode === 'orbital' ? process.env.ORBITAL_PREVIEW_URL : process.env.ESP_PREVIEW_URL) ?? base) + const fixture = !url.searchParams.has('manifest') + if (fixture) { + url.searchParams.set('manifest', '/test-session/manifest.json') + await page.route('**/test-session/*', route => { + const filename = new URL(route.request().url()).pathname.split('/').pop() + if (filename === 'manifest.json') return route.fulfill({ json: { cubes: entries } }) + return route.fulfill({ contentType: 'text/plain', body: cube(filename.split('.')[0]) }) + }) + } + await page.goto(url.href) + const controls = page.getByRole('button', { name: 'Structure controls', exact: true }) + await controls.click() + const finish = page.locator('select').filter({ has: page.locator('option[value="translucent_shell"]') }).filter({ visible: true }) + await finish.waitFor() + assert.deepEqual(await finish.locator('option').evaluateAll(options => options.map(o => o.value)), finishes) + if (mode === 'orbital') { + // Upstream renders translucent, uniformly colored satin lobes with the shell shader. + const opacity = page.getByRole('slider', { name: 'Opacity', exact: true }).first() + await opacity.press('End') + assert.equal(Number(await opacity.inputValue()), 1) + } + // Reopen controls between downloads because the native pane dismisses on outside clicks. + const images = [] + for (const value of finishes) { + if (!await finish.isVisible()) await controls.click() + await finish.selectOption(value) + await page.getByRole('button', { name: 'Save', exact: true }).click() + const pending = page.waitForEvent('download') + await page.getByRole('button', { name: 'PNG image', exact: true }).click() + const download = await pending + assert.equal(await download.failure(), null) + const png = await readFile(await download.path()) + const pixels = await page.evaluate(async base64 => { + const image = new Image() + image.src = 'data:image/png;base64,' + base64 + await image.decode() + const c = document.createElement('canvas') + c.width = c.height = 128 + const ctx = c.getContext('2d') + ctx.drawImage(image, 0, 0, 128, 128) + return Array.from(ctx.getImageData(0, 0, 128, 128).data) + }, png.toString('base64')) + assert.ok(pixels.filter((v, i) => i % 4 !== 3 && v < 220).length > 120, 'molecule appears in PNG') + images.push(pixels) + } + for (let i = 0; i < images.length; i++) for (let j = 0; j < i; j++) { + assert.ok(images[i].some((v,k) => Math.abs(v - images[j][k]) > 4), finishes[i] + ' should differ from ' + finishes[j]) + } + if (fixture && mode === 'esp') { + if (!await finish.isVisible()) await controls.click() + await page.getByRole('button', { name: 'Remove volume Density', exact: true }).click() + await page.locator('.statusbar').getByText('1 volume(s)', { exact: true }).waitFor() + await page.getByRole('button', { name: 'Restore volume Density', exact: true }).click() + await page.locator('.statusbar').getByText('2 volume(s)', { exact: true }).waitFor() + await page.getByRole('button', { name: 'Tools', exact: true }).click() + await page.getByRole('button', { name: 'Approx. ESP extrema', exact: true }).click() + await page.locator('.esp-extrema-list').waitFor() + } + const toolbar = page.locator('.toolbar') + await toolbar.getByRole('button', { name: '切换到中文', exact: true }).click() + assert.equal(await page.locator('html').getAttribute('lang'), 'zh-CN') + await toolbar.getByRole('button', { name: 'Switch to English', exact: true }).click() + assert.equal(await page.locator('html').getAttribute('lang'), 'en') + assert.deepEqual(errors, []) + console.log(mode + ': four native finishes rendered and exported at ' + width + 'px') + } finally { await page.close() } + } +} finally { + await browser.close() + if (server) await server.close() +} diff --git a/frontend/matterviz-viewer/tests/browser/topology-picking.mjs b/frontend/matterviz-viewer/tests/browser/topology-picking.mjs deleted file mode 100644 index 8c8e783a..00000000 --- a/frontend/matterviz-viewer/tests/browser/topology-picking.mjs +++ /dev/null @@ -1,270 +0,0 @@ -// Real StructureScene/Three/Threlte regression. Requires a Playwright installation. -// Run from this viewer with: node tests/browser/topology-picking.mjs -// Optional overrides: PLAYWRIGHT_MODULE, PLAYWRIGHT_CHROMIUM_EXECUTABLE, -// MULTIWFN_VIEWER_ROOT, MATTERVIZ_PACKAGE_ROOT, KEEP_BROWSER_FIXTURE=1. -import assert from 'node:assert/strict' -import fs from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { createRequire } from 'node:module' -import { fileURLToPath, pathToFileURL } from 'node:url' -const viewer = path.resolve(process.env.MULTIWFN_VIEWER_ROOT ?? fileURLToPath(new URL('../../', import.meta.url))) -const require = createRequire(path.join(viewer, 'package.json')) -const { createServer } = await import(pathToFileURL(require.resolve('vite')).href) -const { svelte } = await import(pathToFileURL(require.resolve('@sveltejs/vite-plugin-svelte')).href) -const { chromium } = await import(process.env.PLAYWRIGHT_MODULE - ? pathToFileURL(path.resolve(process.env.PLAYWRIGHT_MODULE)).href - : pathToFileURL(require.resolve('playwright')).href) -const installed = fs.realpathSync(path.join(viewer, 'node_modules/matterviz')) -const metadata = JSON.parse(fs.readFileSync(path.join(installed, 'package.json'), 'utf8')) -const packageSource = path.resolve(process.env.MATTERVIZ_PACKAGE_ROOT ?? installed) -let server -let browser -const evidence = [] -const errors = [] -const warnings = [] -const root = fs.mkdtempSync(path.join(os.tmpdir(), 'multiwfn-topology-picking-')) -const packageRoot = path.join(root, 'matterviz') -try { - // Instrument an exact copy of the installed package without altering node_modules. - // Keeping the fixture source outside node_modules also lets Vite discover and - // prebundle transitive CommonJS dependencies such as Threlte's tweakpane import. - fs.cpSync(path.join(packageSource, 'dist'), path.join(packageRoot, 'dist'), { recursive: true }) - fs.copyFileSync(path.join(packageSource, 'package.json'), path.join(packageRoot, 'package.json')) - fs.writeFileSync(path.join(root, 'package.json'), '{"type":"module"}') - fs.writeFileSync(path.join(root, 'index.html'), '
') - fs.writeFileSync(path.join(root, 'main.js'), "import { mount } from 'svelte'; import App from './App.svelte'; mount(App, { target: document.getElementById('app') });") - fs.copyFileSync(fileURLToPath(new URL('./TopologyPicking.svelte', import.meta.url)), path.join(root, 'App.svelte')) - const dependencyNames = [...Object.keys(metadata.dependencies), 'svelte'] - for (const name of dependencyNames) { - const destination = root + '/node_modules/' + name - fs.mkdirSync(path.dirname(destination), { recursive: true }) - if (!fs.existsSync(destination)) fs.symlinkSync(fs.realpathSync(name === 'svelte' ? viewer + '/node_modules/svelte' : path.dirname(installed) + '/' + name), destination, process.platform === 'win32' ? 'junction' : 'dir') - } - const aliases = [] - aliases.push({ find: 'fixture-matterviz', replacement: packageRoot + '/dist' }) - server = await createServer({ - configFile: false, root, cacheDir: root + '/.vite', - plugins: [{ name: 'capture-real-interactivity', enforce: 'pre', transform(code, id) { - if (!id.endsWith('/dist/structure/StructureScene.svelte')) return - assert.ok(code.includes('import { T, useTask }'), 'StructureScene imports changed; update the test probe') - assert.ok(code.includes(' extras.interactivity()'), 'StructureScene interactivity setup changed; update the test probe') - return code.replace('import { T, useTask }', 'import { T, useTask, useThrelte }') - .replace(' extras.interactivity()', ' window.__interactivity = extras.interactivity()\n window.__threlte = useThrelte()\n window.__project = (xyz) => { const p = new Vector3(...xyz).project(window.__threlte.camera.current); const rect = window.__threlte.canvas.getBoundingClientRect(); return { x: rect.left + (p.x + 1) * rect.width / 2, y: rect.top + (1 - p.y) * rect.height / 2 } }') - } }, svelte()], - resolve: { alias: aliases, dedupe: dependencyNames }, - optimizeDeps: { exclude: ['fixture-matterviz'] }, - server: { host: '127.0.0.1', port: 0, fs: { allow: [root, viewer, packageRoot] }, watch: null, hmr: false }, - }) - await server.listen() - const address = server.httpServer.address() - assert.ok(address && typeof address !== 'string') - browser = await chromium.launch({ - ...(process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE ? { executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE } : {}), - headless: true, - args: ['--no-sandbox', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'], - }) - const page = await browser.newPage({ viewport: { width: 1000, height: 800 } }) - page.on('pageerror', (error) => errors.push(error.message)) - page.on('console', (message) => { - // Existing Threlte passive pointer listeners warn when a context handler calls - // preventDefault. Retain that baseline diagnostic separately from new failures. - if (message.text().includes('Unable to preventDefault inside passive event listener invocation.')) { - warnings.push(message.text()) - return - } - if (message.type() === 'error' || /THREE\.WebGLProgram|VALIDATE_STATUS|WebGL: INVALID/.test(message.text())) errors.push(message.text()) - }) - // A cold Svelte/Vite compile on a mounted filesystem can exceed Playwright's - // 30-second navigation default. - await page.goto(`http://127.0.0.1:${address.port}/`, { timeout: 120000 }) - await page.waitForFunction(() => window.__interactivity?.interactiveObjects.length > 0, undefined, { timeout: 60000 }) - // Allow the actual renderer and ResizeObserver to publish camera/viewport matrices. - await page.waitForTimeout(500) - const settle = () => page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)))) - const snapshot = async (label) => { - const state = await page.evaluate(() => { - const bondMeshes = [] - window.__threlte.scene.traverse((object) => { - if (object.isInstancedMesh && object.geometry?.type === 'CylinderGeometry') { - bondMeshes.push({ mesh: object.uuid, geometry: object.geometry.uuid }) - } - }) - return { - ...window.fixture.state(), - objects: window.__interactivity.interactiveObjects.map((object) => ({ - id: object.uuid, instanced: Boolean(object.isInstancedMesh), - geometry: object.geometry?.type, parentVisible: object.parent?.visible, - })), - bondMeshes: bondMeshes.sort((a, b) => a.mesh.localeCompare(b.mesh)), - menuCount: document.querySelectorAll('.bond-context-menu').length, - } - }) - evidence.push({ label, ...state }) - return state - } - const cylinders = (state) => state.objects.filter((object) => object.geometry === 'CylinderGeometry') - const clickWorld = async (xyz, button = 'right') => { - const point = await page.evaluate((xyz) => window.__project(xyz), xyz) - const target = await page.evaluate(({ x, y }) => document.elementFromPoint(x, y)?.tagName, point) - assert.equal(target, 'CANVAS', `world click ${xyz} must reach canvas, got ${target}`) - await page.mouse.click(point.x, point.y, { button }) - await settle() - } - const initial = await snapshot('ordinary-distance') - assert.equal(cylinders(initial).length, 1) - assert.equal(initial.bondMeshes.length, 2, 'bond body and outline must both be mounted') - await clickWorld([0.35, 0, 0]) - const normal = await snapshot('ordinary-context-positive') - assert.equal(normal.contexts.length, 1, 'visible bond context event must fire') - await page.evaluate(() => window.fixture.topology(true)) - await settle() - const hidden = await snapshot('topology-distance') - assert.equal(cylinders(hidden).length, 0, 'hidden selected bond must leave the actual interactive registry') - assert.deepEqual(hidden.bondMeshes, initial.bondMeshes, 'hiding topology bonds must retain meshes and geometries') - await clickWorld([0.35, 0, 0]) - await clickWorld([-0.7, 0, 0]) - assert.equal((await snapshot('topology-context-blocked')).contexts.length, normal.contexts.length) - - await page.evaluate(() => { window.fixture.topology(false); window.fixture.mode('edit-bonds') }) - await settle() - await clickWorld([0, 0, 0]) - assert.equal((await snapshot('ordinary-edit-menu-open')).menuCount, 1) - await page.evaluate(() => window.fixture.topology(true)) - await settle() - const hiddenMenu = await snapshot('topology-edit-menu-dismissed') - assert.equal(hiddenMenu.menuCount, 0, 'already-open HTML menu must disappear') - assert.equal(cylinders(hiddenMenu).length, 0, 'edit-bond cylinders must be unregistered') - await clickWorld([0, 0, 0], 'left') - assert.deepEqual((await snapshot('topology-no-hidden-delete')).removed, []) - await page.evaluate(() => window.fixture.topology(false)) - await settle() - const restored = await snapshot('ordinary-restored') - assert.equal(restored.menuCount, 0, 'closed menu must not reappear when topology is disabled') - assert.equal(cylinders(restored).length, 1, 'normal edit target must register again') - assert.deepEqual(restored.bondMeshes, initial.bondMeshes) - - await page.evaluate(() => { window.fixture.topology(true); window.fixture.editMode('add'); window.fixture.measured([]) }) - await settle() - await clickWorld([-0.7, 0, 0], 'left') - assert.deepEqual((await snapshot('topology-edit-add-atom')).measured, [0]) - await page.evaluate(() => { window.fixture.mode('distance'); window.fixture.measured([]) }) - await settle() - await clickWorld([-0.7, 0, 0], 'left') - assert.deepEqual((await snapshot('topology-ordered-atom-measurement')).measured, [0]) - - await page.evaluate(() => { window.fixture.partial(true); window.fixture.measured([]) }) - await settle() - await clickWorld([-0.7, 0, 0], 'left') - assert.deepEqual((await snapshot('topology-partial-atom-measurement')).measured, [0]) - await page.evaluate(() => { window.fixture.measured([0, 1]); window.fixture.labels(true) }) - await settle() - const partialBefore = (await snapshot('topology-partial-context-before')).contexts.length - await clickWorld([-0.7, 0, 0]) - await page.locator('.atom-label').first().click({ button: 'right' }) - assert.equal((await snapshot('topology-partial-and-label-context-blocked')).contexts.length, partialBefore) - await page.evaluate(() => window.fixture.topology(false)) - await settle() - await page.locator('.atom-label').first().click({ button: 'right' }) - assert.equal((await snapshot('ordinary-label-context-restored')).contexts.length, partialBefore + 1) - - await page.evaluate(() => { window.fixture.labels(false); window.fixture.atoms(false); window.fixture.measured([]) }) - await settle() - const atomsHidden = await snapshot('ordinary-atoms-disabled') - assert.equal(atomsHidden.objects.filter((object) => object.geometry === 'SphereGeometry').length, 0) - await page.evaluate(() => window.fixture.topology(true)) - await settle() - const forcedAtoms = await snapshot('topology-forces-atoms') - assert.ok(forcedAtoms.objects.some((object) => object.geometry === 'SphereGeometry')) - await clickWorld([-0.7, 0, 0], 'left') - assert.deepEqual((await snapshot('topology-forced-atom-selection')).measured, [0]) - - await page.evaluate(() => { window.fixture.topology(false); window.fixture.atoms(true); window.fixture.mode('edit-bonds'); window.fixture.editMode('delete') }) - await settle() - await clickWorld([0, 0, 0], 'left') - assert.equal((await snapshot('ordinary-delete-positive')).removed.length, 1, 'normal delete must remain functional') - - // Exercise the merge boundary: the topology/surface masks must retain the - // material branch's actual typed-grid meshes and their GPU resources. - await page.evaluate(() => { - window.fixture.resetEdits() - window.fixture.partial(false) - window.fixture.measured([]) - window.fixture.mode('distance') - window.fixture.loadVolume() - }) - await page.waitForFunction(() => { - let surfaces = 0 - window.__threlte.scene.traverse((object) => { - if (object.isMesh && !object.isInstancedMesh && object.geometry?.type === 'BufferGeometry' && - object.material?.type === 'MeshPhongMaterial') surfaces++ - }) - return surfaces === 2 - }, undefined, { timeout: 30000 }) - await settle() - const surfaceSnapshot = async (label) => { - const state = await page.evaluate(() => { - const surfaces = [], bonds = [], atoms = [] - const visible = (object) => { - for (let parent = object; parent; parent = parent.parent) if (!parent.visible) return false - return true - } - window.__threlte.scene.traverse((object) => { - if (!object.isMesh) return - const entry = { - mesh: object.uuid, geometry: object.geometry.uuid, material: object.material.uuid, - visible: visible(object), vertices: object.geometry.getAttribute('position')?.count, - } - if (!object.isInstancedMesh && object.geometry.type === 'BufferGeometry' && - object.material.type === 'MeshPhongMaterial') surfaces.push(entry) - if (object.isInstancedMesh && object.geometry.type === 'CylinderGeometry') bonds.push(entry) - if (object.isInstancedMesh && object.geometry.type === 'SphereGeometry') atoms.push(entry) - }) - for (const entries of [surfaces, bonds, atoms]) entries.sort((a, b) => a.mesh.localeCompare(b.mesh)) - return { surfaces, bonds, atoms } - }) - evidence.push({ label, ...state }) - return state - } - const volumeVisible = await surfaceSnapshot('volume-visible') - assert.equal(volumeVisible.surfaces.length, 2, 'transparent volume must render both surface passes') - assert.ok(volumeVisible.surfaces.every((entry) => entry.vertices > 100 && entry.visible)) - assert.equal(volumeVisible.surfaces[0].geometry, volumeVisible.surfaces[1].geometry, 'both passes reuse the extracted geometry') - assert.notEqual(volumeVisible.surfaces[0].material, volumeVisible.surfaces[1].material, 'front and back use separate materials') - assert.ok(volumeVisible.bonds.length > 0 && volumeVisible.atoms.length > 0) - const volumePixels = await page.locator('canvas').screenshot() - const identity = (entries) => entries.map(({ visible, ...entry }) => entry) - for (const [label, topology, surface, volumeVisibleNow, bondsVisible] of [ - ['volume-topology-hidden', true, false, false, false], - ['volume-quantitative-hidden', false, true, false, true], - ['volume-both-hidden', true, true, false, false], - ['volume-restored', false, false, true, true], - ]) { - await page.evaluate(([topology, surface]) => { - window.fixture.topology(topology) - window.fixture.surface(surface) - }, [topology, surface]) - await settle() - const state = await surfaceSnapshot(label) - for (const kind of ['surfaces', 'bonds', 'atoms']) { - assert.deepEqual(identity(state[kind]), identity(volumeVisible[kind]), `${label}: retain ${kind} mesh, geometry and material`) - } - assert.ok(state.surfaces.every((entry) => entry.visible === volumeVisibleNow), `${label}: correct volume visibility`) - assert.ok(state.bonds.every((entry) => entry.visible === bondsVisible), `${label}: correct ordinary bond visibility`) - assert.ok(state.atoms.every((entry) => entry.visible), `${label}: keep atoms visible`) - if (label === 'volume-quantitative-hidden') { - assert.notDeepEqual(await page.locator('canvas').screenshot(), volumePixels, 'hiding the volume must change real canvas pixels') - } - if (label === 'volume-restored') { - assert.deepEqual(await page.locator('canvas').screenshot(), volumePixels, 'restoring the volume must restore the rendered image') - } - } - assert.deepEqual(errors, [], 'fixture must render without JavaScript or WebGL shader errors') - console.log(JSON.stringify({ result: 'PASS', package: packageSource, checks: evidence.map(({ label }) => label) }, null, 2)) -} finally { - fs.writeFileSync(path.join(root, 'evidence.json'), JSON.stringify({ errors, warnings, evidence }, null, 2)) - await browser?.close() - await server?.close() - if (process.env.KEEP_BROWSER_FIXTURE === '1') console.log(`Browser fixture and evidence: ${root}`) - else fs.rmSync(root, { recursive: true, force: true }) -} diff --git a/frontend/matterviz-viewer/tests/browser/workbench-language.mjs b/frontend/matterviz-viewer/tests/browser/workbench-language.mjs deleted file mode 100644 index a877a433..00000000 --- a/frontend/matterviz-viewer/tests/browser/workbench-language.mjs +++ /dev/null @@ -1,119 +0,0 @@ -// End-to-end locale and naming acceptance against the real molecule/volume preview. -import assert from 'node:assert/strict' -import { mkdir, readFile, writeFile } from 'node:fs/promises' -import path from 'node:path' -const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright') -const preview = process.env.PREVIEW_URL || 'http://127.0.0.1:5197/' -const artifacts = process.env.ARTIFACT_DIR || '/tmp/multiwfn-workbench-language' -await mkdir(artifacts, { recursive: true }) -const browser = await chromium.launch({ executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE, headless: true, - args: ['--no-sandbox', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'] }) -const page = await browser.newPage({ viewport: { width: 1440, height: 960 }, locale: 'en-US', acceptDownloads: true }) -const errors = [], checks = [] -page.on('pageerror', (error) => errors.push(String(error))) -const button = (name) => page.getByRole('button', { name, exact: true }) -const record = (message) => { checks.push(message); console.log('PASS', message) } -const choose = async (label, value) => { - await button(label).click() - await page.getByRole('option', { name: value, exact: true }).click() - await page.getByRole('listbox').waitFor({ state: 'hidden' }) -} -const snapshot = async (chinese, name) => { - await button(chinese ? '保存' : 'Save').click() - const download = page.waitForEvent('download') - await button(chinese ? '保存显示设置' : 'Save display settings').click() - const file = path.join(artifacts, name + '.json') - await (await download).saveAs(file) - await page.getByRole('dialog', { name: chinese ? '保存选项' : 'Save controls', exact: true }).waitFor({ state: 'hidden' }) - return JSON.parse(await readFile(file, 'utf8')) -} -try { - await page.goto(preview, { waitUntil: 'networkidle', timeout: 180000 }) - await page.waitForFunction(() => document.querySelector('.statusbar')?.textContent.includes('2 volume')) - await page.locator('canvas').waitFor() - await button('Tools').click(); await button('Edit atoms and bonds...').click() - assert.equal(await page.locator('html').getAttribute('lang'), 'en') - assert.match(await button('Atom material preset').innerText(), /Renderer default/) - await choose('Scene appearance preset', 'Studio lighting') - await choose('Atom material preset', 'Balanced') - const canvasBounds = await page.locator('canvas').boundingBox() - await page.mouse.move(canvasBounds.x + canvasBounds.width * .55, canvasBounds.y + canvasBounds.height * .5) - await page.mouse.down() - await page.mouse.move(canvasBounds.x + canvasBounds.width * .65, canvasBounds.y + canvasBounds.height * .55, { steps: 12 }) - await page.mouse.up() - await page.waitForTimeout(500) - const before = await snapshot(false, 'locale-before') - assert.equal(before.structureAppearance.lightingRig, 'tmim') - assert.equal(before.structureAppearance.atomStyle, 'current') - await page.evaluate(() => { window.localeTestCanvas = document.querySelector('canvas') }) - await button('切换到中文').click() - await button('视图').waitFor() - assert.equal(await page.locator('html').getAttribute('lang'), 'zh-CN') - assert.match(await button('光照预设').innerText(), /影棚布光/) - assert.match(await button('原子材质预设').innerText(), /均衡/) - assert.match(await page.locator('.statusbar').innerText(), /2 组体数据/) - assert.equal(Number(await page.getByRole('slider', { name: '补光强度', exact: true }).getAttribute('aria-valuenow')), .85) - assert.doesNotMatch(await page.locator('body').innerText(), /TMIM/) - const after = await snapshot(true, 'locale-after') - assert.deepEqual(after, before, 'language switch must preserve every saved scientific and display setting') - assert.equal(await page.evaluate(() => document.querySelector('canvas') === window.localeTestCanvas), true) - assert.equal(await page.locator('canvas').count(), 1) - await page.screenshot({ path: path.join(artifacts, 'language-zh.png') }) - record('中文切换保留同一画布、视角、光照、材质及体数据;旧预设 ID 兼容') - - await button('光照预设').click() - await page.getByRole('option', { name: '标准布光', exact: true }).waitFor() - await page.getByRole('option', { name: '影棚布光', exact: true }).waitFor() - await page.keyboard.press('Escape') - await button('工具').click() - assert.equal(await button('静电势表面').isDisabled(), true) - await button('此会话不支持静电势计算').hover() - await page.getByRole('tooltip', { name: '此会话不支持静电势计算', exact: true }).waitFor() - await page.screenshot({ path: path.join(artifacts, 'language-tools-zh.png') }) - await page.keyboard.press('Escape'); await page.keyboard.press('Escape') - await page.getByRole('tab', { name: '表面', exact: true }).click() - await button('柔和高光').waitFor() - await choose('经典表面材质预设', '拉丝金属') - await page.locator('.inspector-tab-bar').getByRole('button', { name: '打开体数据图层(2)', exact: true }).click() - await page.locator('.layer-panel').getByText('着色依据', { exact: true }).first().waitFor() - assert.match(await page.locator('.layer-panel').innerText(), /Density/) - await page.locator('.layer-panel').getByRole('button', { name: '关闭', exact: true }).click() - await button('视图').click(); await button('二维切片').click() - await page.getByRole('complementary', { name: '二维体数据切片', exact: true }).waitFor() - await button('关闭切片面板').click() - record('中文下拉选项、表面材质、图层、切片及禁用原因可用;数据名称保持原文') - - await button('Switch to English').click() - await button('View').waitFor() - await button('Tools').click(); await button('Edit atoms and bonds...').click() - await page.getByRole('tab', { name: 'Surfaces', exact: true }).click() - assert.match(await button('Original surface material preset').innerText(), /BrushedMetal/) - await page.screenshot({ path: path.join(artifacts, 'language-en.png') }) - await button('切换到中文').click() - await page.reload({ waitUntil: 'networkidle' }) - await button('视图').waitFor() - assert.equal(await page.evaluate(() => localStorage.getItem('multiwfn-ui-language')), 'zh') - assert.match(await page.locator('.statusbar').innerText(), /已载入 2 个体数据图层/) - await page.setViewportSize({ width: 600, height: 820 }) - await button('Switch to English').waitFor() - assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true) - await page.screenshot({ path: path.join(artifacts, 'language-narrow-zh.png') }) - await button('Switch to English').click() - await page.reload({ waitUntil: 'networkidle' }) - await button('View').waitFor() - record('双向切换、刷新后语言记忆及窄屏布局通过') - - const chinese = await browser.newContext({ locale: 'zh-CN', viewport: { width: 1200, height: 800 } }) - const firstVisit = await chinese.newPage() - firstVisit.on('pageerror', (error) => errors.push(String(error))) - await firstVisit.goto(preview, { waitUntil: 'networkidle', timeout: 120000 }) - await firstVisit.getByRole('button', { name: '视图', exact: true }).waitFor() - assert.equal(await firstVisit.locator('html').getAttribute('lang'), 'zh-CN') - await chinese.close() - record('首次打开跟随浏览器中文语言') - assert.deepEqual(errors, []) - await writeFile(path.join(artifacts, 'language-verification.json'), JSON.stringify({ preview, checks, errors }, null, 2)) -} catch (error) { - await page.screenshot({ path: path.join(artifacts, 'language-failure.png') }).catch(() => {}) - console.error({ checks, errors }); throw error -} finally { await browser.close() } diff --git a/frontend/matterviz-viewer/tests/browser/workbench-ui.mjs b/frontend/matterviz-viewer/tests/browser/workbench-ui.mjs deleted file mode 100644 index 7d6e05b5..00000000 --- a/frontend/matterviz-viewer/tests/browser/workbench-ui.mjs +++ /dev/null @@ -1,152 +0,0 @@ -// Browser acceptance for the actual workbench, using a real molecule manifest. -// Start the preview first; Playwright is supplied by the developer environment. -import assert from 'node:assert/strict' -import { mkdir, readFile, writeFile } from 'node:fs/promises' -import path from 'node:path' -const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright') -const preview = process.env.PREVIEW_URL || 'http://127.0.0.1:5197/' -const artifacts = process.env.ARTIFACT_DIR || '/tmp/multiwfn-workbench-ui' -await mkdir(artifacts, { recursive: true }) -const browser = await chromium.launch({ - executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE, - headless: true, - args: ['--no-sandbox', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'], -}) -const checks = [] -const record = (message) => { checks.push(message); console.log('PASS', message) } -const errors = [] -const page = await browser.newPage({ viewport: { width: 1440, height: 960 }, acceptDownloads: true, locale: 'en-US' }) -page.on('pageerror', (error) => errors.push(String(error))) -const button = (name) => page.getByRole('button', { name, exact: true }) -const choose = async (label, name) => { - await page.getByRole('button', { name: label, exact: true }).click() - await page.getByRole('option', { name, exact: true }).click() - await page.getByRole('listbox').waitFor({ state: 'hidden' }) - await page.waitForFunction(({ label, name }) => [...document.querySelectorAll('[data-slot=select-trigger]')].some((e) => e.getAttribute('aria-label') === label && e.textContent.includes(name)), { label, name }) -} -const checkCanvas = async () => { - assert.equal(await page.locator('canvas').count(), 1) - assert.equal(await page.evaluate(() => document.querySelector('canvas') === window.workbenchTestCanvas), true) -} -try { - await page.goto(preview, { waitUntil: 'networkidle', timeout: 120000 }) - await page.locator('canvas').waitFor() - await button('Tools').click(); await button('Edit atoms and bonds...').click() - await page.waitForFunction(() => document.querySelector('.statusbar')?.textContent?.includes('2 volume')) - await page.evaluate(() => { window.workbenchTestCanvas = document.querySelector('canvas') }) - const layout = await page.locator('.inspector-content').evaluate((e) => { - const pane = e.closest('aside').getBoundingClientRect(); const content = e.getBoundingClientRect() - return { fits: content.right <= pane.right + 1 && content.left >= pane.left, width: content.width } - }) - assert.equal(layout.fits, true) - assert.ok(layout.width > 250) - assert.ok(await page.locator('[data-slot="slider-track"]').first().evaluate((e) => e.getBoundingClientRect().height > 0)) - record('Real molecule, one canvas, readable inspector and visible slider tracks') - - for (const name of ['View', 'Tools', 'Save']) { - await button(name).click() - await page.getByRole('dialog', { name: `${name} controls` }).waitFor() - await page.keyboard.press('Escape') - await page.getByRole('dialog', { name: `${name} controls` }).waitFor({ state: 'hidden' }) - assert.equal(await button(name).evaluate((e) => document.activeElement === e), true) - } - await button('View').focus() - await page.keyboard.press('Enter') - await page.getByRole('spinbutton', { name: 'Rotation step', exact: true }).waitFor() - await page.keyboard.press('Escape') - await button('View').click() - await button('Save').click() - await page.getByRole('dialog', { name: 'View controls' }).waitFor({ state: 'hidden' }) - await page.locator('.brand').click() - await page.getByRole('dialog', { name: 'Save controls' }).waitFor({ state: 'hidden' }) - record('Menus: keyboard open, Escape, focus return, outside click and switching') - - const tab = page.getByRole('tab', { name: 'Structure', exact: true }) - await tab.focus(); await page.keyboard.press('ArrowRight') - assert.equal(await page.getByRole('tab', { name: 'Surfaces', exact: true }).getAttribute('aria-selected'), 'true') - await page.keyboard.press('ArrowLeft') - assert.equal(await tab.getAttribute('aria-selected'), 'true') - const ambient = page.getByRole('slider', { name: 'Ambient light', exact: true }) - await ambient.focus(); await page.keyboard.press('ArrowRight') - assert.equal(Number(await ambient.getAttribute('aria-valuenow')), 0.73) - await choose('Scene appearance preset', 'Studio lighting') - assert.equal(Number(await ambient.getAttribute('aria-valuenow')), 1.25) - assert.equal(Number(await page.getByRole('slider', { name: 'Fill light', exact: true }).getAttribute('aria-valuenow')), .85) - await choose('Scene appearance preset', 'Standard lighting') - assert.equal(Number(await page.getByRole('slider', { name: 'Fill light', exact: true }).getAttribute('aria-valuenow')), .38) - assert.equal(Number(await page.getByRole('slider', { name: 'Rim light', exact: true }).getAttribute('aria-valuenow')), .24) - await choose('Scene appearance preset', 'Studio lighting') - await choose('Atom material preset', 'Metallic') - await checkCanvas() - record('Keyboard tabs and sliders; Studio/standard switches all four lights; atom finish') - - await button('Save').click() - const downloadEvent = page.waitForEvent('download') - await button('Save display settings').click() - const download = await downloadEvent - const settingsPath = path.join(artifacts, 'display-settings.json') - await download.saveAs(settingsPath) - const saved = JSON.parse(await readFile(settingsPath, 'utf8')) - assert.equal(saved.structureAppearance.lightingRig, 'tmim') - assert.equal(saved.structureAppearance.fillLight, .85) - assert.equal(saved.structureAppearance.atomStyle, 'metallic') - await choose('Scene appearance preset', 'Standard lighting') - await choose('Atom material preset', 'Matte') - await page.locator('input[type="file"][accept="application/json,.json"]').setInputFiles(settingsPath) - await page.waitForFunction(() => document.querySelector('[aria-label="Scene appearance preset"]')?.textContent?.includes('Studio lighting')) - assert.match(await page.getByRole('button', { name: 'Atom material preset', exact: true }).innerText(), /Metallic/) - await checkCanvas() - record('Display settings download and restore lighting and atom finish on the same canvas') - - await choose('Atom material preset', 'Balanced') - await page.locator('.inspector-content').evaluate((e) => e.scrollTop = 0) - await page.screenshot({ path: path.join(artifacts, 'molecule.png') }) - await page.getByRole('tab', { name: 'Surfaces', exact: true }).click() - await choose('Original surface material preset', 'BrushedMetal') - assert.match(await page.getByRole('button', { name: 'Original surface material preset', exact: true }).innerText(), /BrushedMetal/) - await button('Soft gloss').click() - assert.equal(await button('Soft gloss').getAttribute('aria-pressed'), 'true') - await page.locator('.inspector-tab-bar').getByRole('button', { name: 'Open volume layers (2)', exact: true }).click() - await page.locator('.layer-panel').waitFor() - await page.locator('.layer-panel .layer-heading input[type="checkbox"]').first().check() - await page.locator('.layer-panel').getByRole('button', { name: 'Close', exact: true }).click() - await checkCanvas() - await page.screenshot({ path: path.join(artifacts, 'surface.png') }) - record('Original surface presets, smooth finish and volume visibility controls') - - await button('Tools').click() - const disabled = page.getByRole('dialog', { name: 'Tools controls' }).getByRole('button', { name: 'ESP surface', exact: true }) - assert.equal(await disabled.isDisabled(), true) - const info = page.getByRole('button', { name: 'No ESP calculation is available in this session', exact: true }) - for (let step = 0; step < 20 && !(await info.evaluate((e) => document.activeElement === e)); step++) await page.keyboard.press('Tab') - assert.equal(await info.evaluate((e) => document.activeElement === e), true) - await page.getByRole('tooltip', { name: 'No ESP calculation is available in this session', exact: true }).waitFor() - await page.screenshot({ path: path.join(artifacts, 'tools.png') }) - await page.keyboard.press('Escape'); await page.keyboard.press('Escape') - record('Unavailable backend actions remain disabled with a keyboard accessible reason') - - await page.setViewportSize({ width: 600, height: 820 }) - await button('Tools').click(); await button('Edit atoms and bonds...').click() - await page.getByRole('dialog', { name: 'Tools controls', exact: true }).waitFor({ state: 'hidden' }) - assert.equal(await page.getByRole('tab', { name: 'Structure', exact: true }).evaluate((e) => { const r = e.getBoundingClientRect(); return e.contains(document.elementFromPoint(r.x + r.width / 2, r.y + r.height / 2)) }), true) - await page.screenshot({ path: path.join(artifacts, 'narrow.png') }) - assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true) - await page.locator('.inspector-header').getByRole('button', { name: 'Close inspector', exact: true }).click() - await page.screenshot({ path: path.join(artifacts, 'narrow-canvas.png') }) - await button('View').click() - await page.waitForFunction(() => { const r = document.querySelector('#workbench-menu-view')?.getBoundingClientRect(); return r && r.x >= 0 && r.right <= innerWidth }) - const bounds = await page.getByRole('dialog', { name: 'View controls' }).boundingBox() - assert.ok(bounds.x >= 0 && bounds.x + bounds.width <= 601) - await page.keyboard.press('Escape') - await checkCanvas() - record('600 px layout: no page overflow, collapsible inspector and viewport-bounded menu') - assert.deepEqual(errors, []) - await writeFile(path.join(artifacts, 'verification.json'), JSON.stringify({ preview, checks, errors }, null, 2)) - console.log(JSON.stringify({ checks, errors, artifacts }, null, 2)) -} catch (error) { - await page.screenshot({ path: path.join(artifacts, 'failure.png') }).catch(() => {}) - console.error({ checks, errors }) - throw error -} finally { - await browser.close() -} diff --git a/frontend/matterviz-viewer/tests/camera-esp-vendor.test.ts b/frontend/matterviz-viewer/tests/camera-esp-vendor.test.ts deleted file mode 100644 index fe9c678c..00000000 --- a/frontend/matterviz-viewer/tests/camera-esp-vendor.test.ts +++ /dev/null @@ -1,126 +0,0 @@ -import assert from 'node:assert/strict' -import { execFileSync } from 'node:child_process' -import { readFile } from 'node:fs/promises' -import test from 'node:test' -import { compileModule } from 'svelte/compiler' -import { Color } from 'three' -import ts from 'typescript' -import { createServer } from 'vite' -import { ESP_COLORS, ESP_COLORMAP, surface_colormap } from '../src/esp.ts' -import { create_workbench_state, parse_workbench_state, restore_workbench_state } from '../src/state.ts' - -test('native control edits survive camera snapshots and accept external reset', async () => { - const source = await readFile(new URL('../node_modules/matterviz/dist/structure/Structure.svelte', import.meta.url), 'utf8') - const start = source.indexOf(' $effect.pre(() => {') - const end = source.indexOf('\n })', start) + '\n })'.length - assert.ok(start > 0 && end > start) - // Run the installed component's actual synchronization effect with Svelte's - // reactive runtime, including the parent's snapshot/replacement behavior. - const fixture = ` - import assert from 'node:assert/strict' - import { flushSync, untrack } from 'svelte' - let scene_props = $state({ auto_rotate: 0, camera_control_mode: 'arcball' }) - let scene_props_in = $state({ auto_rotate: 0 }) - let lattice_props = $state({ cell_edge_opacity: 0.5 }) - let lattice_props_in = $state({ cell_edge_opacity: 0.4 }) - const cleanup = $effect.root(() => { ${source.slice(start, end)} }) - flushSync() - assert.equal(scene_props_in, scene_props) - assert.equal(lattice_props_in, lattice_props) - scene_props.auto_rotate = 0.8 - lattice_props.cell_edge_opacity = 0.7 - flushSync() - for (let frame = 0; frame < 120; frame++) { - scene_props_in = { ...scene_props_in, camera_position: [frame, 0, 1] } - flushSync() - assert.equal(scene_props.auto_rotate, 0.8) - assert.equal(scene_props_in.auto_rotate, 0.8) - assert.equal(lattice_props_in.cell_edge_opacity, 0.7) - } - scene_props_in = { ...scene_props_in, auto_rotate: 0 } - flushSync() - assert.equal(scene_props.auto_rotate, 0) - scene_props.auto_rotate = 1.2 - flushSync() - const suspended = scene_props_in.auto_rotate - scene_props_in = { ...scene_props_in, auto_rotate: 0 } - flushSync() - scene_props_in = { ...scene_props_in, auto_rotate: suspended } - flushSync() - assert.equal(scene_props.auto_rotate, 1.2) - cleanup() - ` - const compiled = compileModule(fixture, { filename: 'camera-sync.svelte.js', generate: 'client' }) - execFileSync(process.execPath, ['--conditions=browser', '--input-type=module', '-e', compiled.js.code], { - cwd: new URL('..', import.meta.url), timeout: 15000, stdio: 'pipe', - }) -}) - -test('ESP palette reaches the actual linear-space vertex colors and preserves other maps', async () => { - const vite = await createServer({ - configFile: false, server: { middlewareMode: true, watch: null, ws: false }, - appType: 'custom', optimizeDeps: { noDiscovery: true }, - }) - try { - const { get_d3_interpolator } = await vite.ssrLoadModule('/node_modules/matterviz/dist/colors/index.js') - const { scalars_to_vertex_colors, ISO_COLORMAPS, auto_color_config } = await vite.ssrLoadModule('/node_modules/matterviz/dist/isosurface/coloring.js') - const interpolate = get_d3_interpolator(ESP_COLORMAP) - for (const [t, expected] of [[0, ESP_COLORS.negative], [0.5, ESP_COLORS.zero], [1, ESP_COLORS.positive]] as const) { - assert.equal(interpolate(t), expected) - } - assert.equal(interpolate(-1), ESP_COLORS.negative) - assert.equal(interpolate(2), ESP_COLORS.positive) - assert.ok(ISO_COLORMAPS.includes(ESP_COLORMAP)) - const colorBar = await readFile(new URL('../node_modules/matterviz/dist/plot/core/components/ColorBar.svelte', import.meta.url), 'utf8') - assert.match(colorBar, /func_name === `interpolateTransFlag` \|\| func_name in d3_sc/) - assert.match(colorBar, /interpolator = get_d3_interpolator\(func_name as D3InterpolateName\)/) - const out = new Float32Array(9) - const colors = scalars_to_vertex_colors(new Float32Array([-1, 0, 1]), { colormap: ESP_COLORMAP, color_range: [-1, 1] }, out) - assert.equal(colors, out) - for (const [idx, css] of [ESP_COLORS.negative, ESP_COLORS.zero, ESP_COLORS.positive].entries()) { - const expected = new Color(css).toArray() - expected.forEach((channel, channelIdx) => assert.ok(Math.abs(colors[3 * idx + channelIdx] - channel) < 1e-7)) - } - assert.equal(auto_color_config({ min: -1, max: 1, abs_max: 1 }).colormap, 'interpolateRdBu') - assert.equal(surface_colormap({ path: '/api/volume/2', analysisKind: 'esp-potential' }, 'interpolateRdBu'), ESP_COLORMAP) - assert.equal(surface_colormap({ path: 'generic.cube' }, 'interpolateViridis'), 'interpolateViridis') - } finally { - await vite.close() - } -}) - -test('Trans Flag ESP mapping round-trips through workbench state', () => { - const entries = [ - { path: 'density.cube', analysisKind: 'esp-density' }, - { path: 'potential.cube', analysisKind: 'esp-potential' }, - ] - const state = create_workbench_state({ - manifest: {}, entries, activeVolume: 0, atomSupercell: '1x1x1', - showBoundaryAtoms: false, showUnitCell: false, - isosurfaceSettings: { layers: [{ volume_idx: 0, color_volume_idx: 1, colormap: ESP_COLORMAP, color_range: [-0.05, 0.05] }] }, - }) - const parsed = parse_workbench_state(JSON.parse(JSON.stringify(state))) - const restored = restore_workbench_state(parsed, { entries, isosurfaceSettings: { layers: [{ volume_idx: 0 }, { volume_idx: 1 }] } }) - assert.equal(restored.isosurfaceSettings.layers?.[0].colormap, ESP_COLORMAP) - assert.deepEqual(restored.isosurfaceSettings.layers?.[0].color_range, [-0.05, 0.05]) - state.volumes[0].colormap = 'not-a-colormap' - assert.equal(parse_workbench_state(state).volumes[0].colormap, undefined) -}) - -test('direct signed ESP surfaces use the same sign colors as mapped ESP', async () => { - const app = await readFile(new URL('../src/App.svelte', import.meta.url), 'utf8') - const start = app.indexOf(' const layer_for_entry =') - const end = app.indexOf('\n const parse_volume_entry', start) - assert.ok(start > 0 && end > start) - const declaration = ts.transpileModule(app.slice(start, end), { - compilerOptions: { target: ts.ScriptTarget.ESNext, module: ts.ModuleKind.ESNext }, - }).outputText - const createLayer = new Function('ESP_COLORS', `${declaration}; return layer_for_entry`)(ESP_COLORS) - const esp = createLayer({ mode: 'signed', analysisKind: 'esp-potential' }, 1) - assert.equal(esp.color, ESP_COLORS.positive) - assert.equal(esp.negative_color, ESP_COLORS.negative) - assert.equal(esp.show_negative, true) - const generic = createLayer({ mode: 'signed' }, 0) - assert.equal(generic.color, '#2563eb') - assert.equal(generic.negative_color, '#dc2626') -}) diff --git a/frontend/matterviz-viewer/tests/camera.test.ts b/frontend/matterviz-viewer/tests/camera.test.ts deleted file mode 100644 index 06f149a9..00000000 --- a/frontend/matterviz-viewer/tests/camera.test.ts +++ /dev/null @@ -1,149 +0,0 @@ -import assert from 'node:assert/strict' -import test from 'node:test' -import { camera_basis, camera_update_matches, normalize_camera_pose, normalize_camera_step, pan_camera, rotate_camera, zoom_camera, type CameraDirection, type CameraPose } from '../src/camera.ts' - -const pose = (projection: CameraPose['projection'] = 'perspective'): CameraPose => ({ - position: [4, 3, 8], - target: [1, -2, 0.5], - up: [0, 1, 0], - projection, - ...(projection === 'orthographic' ? { zoom: 2.5 } : {}), -}) - -const close_vec = (actual: number[], expected: number[], tolerance = 1e-9): void => { - assert.equal(actual.length, expected.length) - actual.forEach((value, idx) => assert.ok(Math.abs(value - expected[idx]) < tolerance, `${value} != ${expected[idx]}`)) -} - -test('normalizes camera bases and handles parallel up vectors', () => { - const normalized = normalize_camera_pose({ ...pose(), up: [3, 5, 2] }) - assert.ok(normalized) - const basis = camera_basis(normalized) - assert.ok(Math.abs(Math.hypot(...basis.right) - 1) < 1e-12) - assert.ok(Math.abs(Math.hypot(...basis.up) - 1) < 1e-12) - assert.ok(Math.abs(Math.hypot(...basis.back) - 1) < 1e-12) - assert.ok(Math.abs(basis.right.reduce((sum, value, idx) => sum + value * basis.up[idx], 0)) < 1e-12) - assert.ok(normalize_camera_pose({ ...pose(), up: [3, 5, 7.5] })) -}) - -test('opposite semantic rotations are inverse', () => { - for (const [positive, negative] of [ - ['up', 'down'], - ['left', 'right'], - ['clockwise', 'counterclockwise'], - ] as const) { - const initial = pose() - const restored = rotate_camera(rotate_camera(initial, positive, 17.5), negative, 17.5) - close_vec(restored.position, initial.position) - close_vec(restored.target, initial.target) - close_vec(restored.up, normalize_camera_pose(initial)?.up ?? initial.up) - } -}) - -test('four repeated quarter-turns return the original pose', () => { - for (const direction of ['up', 'left', 'clockwise'] as const) { - let current = pose() - for (let index = 0; index < 4; index += 1) current = rotate_camera(current, direction, 90) - close_vec(current.position, pose().position, 1e-8) - close_vec(current.up, normalize_camera_pose(pose())?.up ?? pose().up, 1e-8) - } -}) - -test('rotations preserve target, camera distance, and orthonormal basis', () => { - for (const direction of ['up', 'down', 'left', 'right', 'clockwise', 'counterclockwise'] as CameraDirection[]) { - const initial = pose('orthographic') - const rotated = rotate_camera(initial, direction, 37) - close_vec(rotated.target, initial.target) - assert.ok(Math.abs(Math.hypot(...rotated.position.map((value, idx) => value - rotated.target[idx])) - Math.hypot(...initial.position.map((value, idx) => value - initial.target[idx]))) < 1e-9) - const basis = camera_basis(rotated) - assert.ok(Math.abs(Math.hypot(...basis.right) - 1) < 1e-12) - assert.ok(Math.abs(Math.hypot(...basis.up) - 1) < 1e-12) - assert.ok(Math.abs(Math.hypot(...basis.back) - 1) < 1e-12) - assert.ok(Math.abs(basis.right.reduce((sum, value, idx) => sum + value * basis.up[idx], 0)) < 1e-12) - } -}) - -test('screen-following directions have the expected projection sign', () => { - const initial: CameraPose = { position: [0, 0, 10], target: [0, 0, 0], up: [0, 1, 0], projection: 'perspective' } - const point: [number, number, number] = [0.25, 0.15, 1] - const screen = (camera: CameraPose): [number, number] => { - const basis = camera_basis(camera) - return [ - point.reduce((sum, value, idx) => sum + value * basis.right[idx], 0), - point.reduce((sum, value, idx) => sum + value * basis.up[idx], 0), - ] - } - const base = screen(initial) - assert.ok(screen(rotate_camera(initial, 'up', 5))[1] > base[1]) - assert.ok(screen(rotate_camera(initial, 'down', 5))[1] < base[1]) - assert.ok(screen(rotate_camera(initial, 'left', 5))[0] < base[0]) - assert.ok(screen(rotate_camera(initial, 'right', 5))[0] > base[0]) -}) - -test('roll rotates screen orientation while preserving view direction', () => { - const initial: CameraPose = { position: [0, 0, 10], target: [0, 0, 0], up: [0, 1, 0], projection: 'orthographic', zoom: 2 } - const rolled = rotate_camera(initial, 'clockwise', 90) - close_vec(rolled.position, initial.position) - close_vec(rolled.target, initial.target) - close_vec(rolled.up, [-1, 0, 0], 1e-10) - assert.equal(rolled.zoom, initial.zoom) -}) - -test('camera-relative pan preserves view direction and is reversible', () => { - const initial = pose() - const moved = pan_camera(initial, 0.4, -0.25) - close_vec(moved.position.map((value, idx) => value - moved.target[idx]), initial.position.map((value, idx) => value - initial.target[idx])) - const restored = pan_camera(moved, -0.4, 0.25) - close_vec(restored.position, initial.position) - close_vec(restored.target, initial.target) -}) - -test('perspective and orthographic zoom use reciprocal inverse steps', () => { - const perspective = pose('perspective') - const perspectiveRestored = zoom_camera(zoom_camera(perspective, 12, 'in'), 12, 'out') - close_vec(perspectiveRestored.position, perspective.position) - const orthographic = pose('orthographic') - const orthographicRestored = zoom_camera(zoom_camera(orthographic, 12, 'in'), 12, 'out') - assert.ok(Math.abs((orthographicRestored.zoom ?? 0) - (orthographic.zoom ?? 0)) < 1e-12) -}) - -test('invalid and degenerate camera inputs are rejected or left unchanged', () => { - assert.equal(normalize_camera_pose({ ...pose(), position: [1, 1, 1], target: [1, 1, 1] }), undefined) - assert.deepEqual(rotate_camera(pose(), 'up', Number.NaN), pose()) - assert.deepEqual(rotate_camera(pose(), 'invalid' as CameraDirection, 15), pose()) - assert.deepEqual(pan_camera(pose(), Number.POSITIVE_INFINITY, 1), pose()) - assert.deepEqual(zoom_camera(pose(), 0, 'in'), pose()) -}) - -test('normalizes camera steps to finite per-control limits', () => { - assert.equal(normalize_camera_step(15, 'rotation'), 15) - assert.equal(normalize_camera_step(-1, 'rotation'), 0.1) - assert.equal(normalize_camera_step(1000, 'rotation'), 180) - assert.equal(normalize_camera_step(0, 'pan'), 0.001) - assert.equal(normalize_camera_step(1000, 'pan'), 100) - assert.equal(normalize_camera_step(0, 'zoom'), 0.1) - assert.equal(normalize_camera_step(1000, 'zoom'), 500) - assert.equal(normalize_camera_step('', 'rotation'), undefined) - assert.equal(normalize_camera_step(Number.NaN, 'pan'), undefined) - assert.equal(normalize_camera_step(Number.POSITIVE_INFINITY, 'zoom'), undefined) -}) - -test('camera state updates are idempotent within numerical tolerance', () => { - const current = { - camera_position: [1, 2, 3] as [number, number, number], - camera_target: [0, 0, 0] as [number, number, number], - camera_up: [0, 1, 0] as [number, number, number], - camera_zoom: 2, - camera_projection: 'orthographic' as const, - } - assert.equal(camera_update_matches(current, { - camera_position: [1 + 5e-13, 2, 3], - camera_target: [0, 0, 0], - camera_up: [0, 1, 0], - camera_zoom: 2, - }), true) - assert.equal(camera_update_matches(current, { ...current, camera_position: [1.01, 2, 3] }), false) - assert.equal(camera_update_matches(current, { ...current, camera_target: [0, 0.01, 0] }), false) - assert.equal(camera_update_matches(current, { ...current, camera_up: [0.01, 1, 0] }), false) - assert.equal(camera_update_matches(current, { camera_zoom: undefined }), false) -}) diff --git a/frontend/matterviz-viewer/tests/color-scale.test.ts b/frontend/matterviz-viewer/tests/color-scale.test.ts deleted file mode 100644 index fab318e3..00000000 --- a/frontend/matterviz-viewer/tests/color-scale.test.ts +++ /dev/null @@ -1,157 +0,0 @@ -import assert from 'node:assert/strict' -import test from 'node:test' -import { createServer } from 'vite' -import { Color, SRGBColorSpace } from 'three' -import { color_stop_hex, color_stop_interpolator, color_stops_gradient, normalize_color_stops } from 'matterviz/colors/stops' -import { COLOR_SCALE_PRESETS, legacy_color_scale, migrate_color_scale, normalize_color_scale, preset_color_scale, volume_color_scale } from '../src/color-scale.ts' -import { copy_rep, create_rep, migrate_reps, normalize_rep, rep_surface_settings } from '../src/reps.ts' -import { create_workbench_state, parse_workbench_state, restore_workbench_state } from '../src/state.ts' - -const stops = [{ position: 0.1, color: '#ff0000' }, { position: 0.3, color: '#00ff00' }, { position: 0.8, color: '#0000ff' }] - -test('uneven color stops interpolate in sRGB and extend the nearest endpoint', () => { - const interpolate = color_stop_interpolator(stops), output = [0, 0, 0] - assert.equal(interpolate(0.2, output), output) - assert.ok(Math.abs(output[0] - 0.5) < 1e-12) - assert.ok(Math.abs(output[1] - 0.5) < 1e-12) - assert.equal(output[2], 0) - assert.equal(color_stop_hex(stops, 0.3), '#00ff00') - assert.deepEqual(interpolate(-1), [1, 0, 0]) - assert.deepEqual(interpolate(1), [0, 0, 1]) - assert.deepEqual(interpolate(0.3), [0, 1, 0]) - assert.equal(color_stops_gradient(stops, 'to top'), 'linear-gradient(to top in srgb, #ff0000 10%, #00ff00 30%, #0000ff 80%)') -}) - -test('inserting a sampled point preserves the scale within one 8-bit color step', () => { - const expanded = [...stops, { position: 0.55, color: color_stop_hex(stops, 0.55) }] - const before = color_stop_interpolator(stops), after = color_stop_interpolator(expanded) - for (let i = 0; i <= 100; i++) before(i / 100).forEach((channel, c) => assert.ok(Math.abs(channel - after(i / 100)[c]) <= 1 / 255)) -}) - -test('color-stop validation bounds allocation and rejects ambiguous or malformed scales', () => { - for (const invalid of [undefined, [], [stops[0]], Array.from({ length: 33 }, (_, i) => ({ ...stops[0], position: i / 32 }))]) - assert.throws(() => normalize_color_stops(invalid), /between 2 and 32/) - for (const position of [-0.1, 1.1, NaN, Infinity, '0.2', undefined]) - assert.throws(() => normalize_color_stops([{ ...stops[0], position }, stops[2]]), /between 0% and 100%/) - for (const color of ['#fff', 'red', '#12345z', 'url(example)', null]) - assert.throws(() => normalize_color_stops([{ ...stops[0], color }, stops[2]]), /six-digit hex/) - assert.throws(() => normalize_color_stops([stops[0], stops[0]]), /distinct/) - const input = [{ position: 1, color: '#AABBCC' }, { position: 0, color: '#FFFFFF' }] - assert.deepEqual(normalize_color_stops(input), [{ position: 0, color: '#ffffff' }, { position: 1, color: '#aabbcc' }]) - assert.equal(input[0].color, '#AABBCC', 'normalization must not mutate caller data') - assert.equal(normalize_color_stops(Array.from({ length: 32 }, (_, i) => ({ color: '#abcdef', position: i / 31 }))).length, 32) -}) - -test('every preset loads independent editable points and edited presets become custom', () => { - for (const { name } of COLOR_SCALE_PRESETS) { - const first = preset_color_scale(`interpolate${name}`), second = preset_color_scale(`interpolate${name}`) - assert.deepEqual(normalize_color_scale(first), first) - assert.equal(first.stops[0].position, 0) - assert.equal(first.stops.at(-1)!.position, 1) - first.stops[0].position = 0.01 - assert.equal(second.stops[0].position, 0) - assert.equal(normalize_color_scale(first).preset, 'custom') - assert.equal(normalize_color_scale({ ...second, preset: 'custom' }).preset, 'custom') - } -}) - -test('legacy pink/white/blue retains physical-zero white and one-sided ranges', () => { - const asymmetric = legacy_color_scale('interpolateTransFlag', [-0.02, 0.08]) - assert.equal(asymmetric.preset, 'custom') - assert.ok(Math.abs(asymmetric.stops[1].position - 0.2) < 1e-12) - assert.equal(color_stop_hex(asymmetric.stops, 0.2), '#ffffff') - assert.deepEqual(legacy_color_scale('interpolateTransFlag', [0.08, -0.02]), asymmetric) - assert.deepEqual(legacy_color_scale('interpolateTransFlag', [-1, 1]), preset_color_scale('interpolateTransFlag')) - for (const [range, colors] of [ - [[0, 1], ['#ffffff', '#5bcefa']], - [[-1, 0], ['#f5a9b8', '#ffffff']], - [[1, 1], ['#ffffff', '#ffffff']], - ] as const) assert.deepEqual(legacy_color_scale('interpolateTransFlag', [...range]).stops.map(stop => stop.color), colors) -}) - -test('custom scales copy independently, persist with the scene and reach the renderer unchanged', () => { - const rep = create_rep({ kind: 'volume', index: 0, path: 'density' }, 'density') - rep.volume.color_volume_idx = 1; rep.volume.colorSourcePath = 'esp' - rep.volume.colorScale = { preset: 'custom', stops: structuredClone(stops) } - const duplicate = copy_rep(rep, 'copy') - duplicate.volume.colorScale!.stops[1].color = '#ffffff' - assert.equal(rep.volume.colorScale.stops[1].color, '#00ff00') - assert.deepEqual(rep_surface_settings(rep).layers![0].color_stops, stops) - rep.volume.color_range = [6, -2] - assert.deepEqual(rep_surface_settings(rep).layers![0].color_range, [-2, 6]) - const entries = [{ path: 'density' }, { path: 'esp' }], isosurfaceSettings = rep_surface_settings(rep) - const saved = create_workbench_state({ representations: { items: [rep, duplicate], selectedId: 'copy' }, manifest: {}, entries, isosurfaceSettings, - activeVolume: 0, atomSupercell: '1x1x1', showBoundaryAtoms: true, showUnitCell: false }) - const restored = restore_workbench_state(parse_workbench_state(JSON.parse(JSON.stringify(saved))), { entries: [...entries].reverse(), isosurfaceSettings }).representations! - assert.deepEqual(restored.items[0].volume.colorScale, rep.volume.colorScale) - assert.deepEqual(restored.items[1].volume.colorScale, duplicate.volume.colorScale) - assert.equal(restored.items[0].volume.color_volume_idx, 0) - assert.throws(() => normalize_rep({ ...rep, volume: { ...rep.volume, colorScale: { stops: [stops[0], stops[0]] } } }), /distinct/) -}) - -test('old Reps and imported renderer layers migrate their actual colors', () => { - assert.equal(legacy_color_scale().preset, 'interpolateViridis', 'unspecified legacy maps use the renderer default') - const rep = create_rep({ kind: 'volume', index: 0 }, 'legacy') - delete rep.volume.colorScale - rep.volume.colormap = 'interpolateTransFlag'; rep.volume.color_range = [-1, 3] - assert.deepEqual(normalize_rep(rep)!.volume.colorScale, legacy_color_scale('interpolateTransFlag', [-1, 3])) - rep.volume.color_stops = stops - assert.deepEqual(normalize_rep(rep)!.volume.colorScale!.stops, stops) - assert.deepEqual(volume_color_scale(rep.volume).stops, stops) -}) - -test('migrated percentages stay fixed when the range changes, before and after saving', () => { - const rep = create_rep({ kind: 'volume', index: 0 }, 'legacy') - delete rep.volume.colorScale - rep.volume.colormap = 'interpolateTransFlag'; rep.volume.color_range = [-1, 3] - const settings = { ...rep_surface_settings(rep), layers: [rep.volume] } - const migrated = migrate_reps({}, settings, [{ path: 'density' }], false).items[1] - assert.equal(migrated.volume.colorScale!.stops[1].position, 0.25) - const restored = normalize_rep(JSON.parse(JSON.stringify(migrated)))! - migrated.volume.color_range = [-1, 1]; restored.volume.color_range = [-1, 1] - assert.equal(rep_surface_settings(migrated).layers![0].color_stops![1].position, 0.25) - assert.deepEqual(rep_surface_settings(restored).layers![0].color_stops, rep_surface_settings(migrated).layers![0].color_stops) -}) - -test('legacy automatic TransFlag waits for the rendered range, including saved hidden Reps', () => { - const rep = create_rep({ kind: 'volume', index: 0 }, 'legacy') - delete rep.volume.colorScale - rep.volume.colormap = 'interpolateTransFlag' - const migrated = migrate_reps({}, { ...rep_surface_settings(rep), layers: [rep.volume] }, [{ path: 'density' }], false).items[1] - const restored = normalize_rep(JSON.parse(JSON.stringify(migrated)))! - assert.equal(restored.volume.colorScale, undefined) - assert.equal(rep_surface_settings(restored).layers![0].color_stops, undefined, 'keep the renderer legacy zero normalization while awaiting the range') - for (const range of [[0.1, 0.4], [-0.4, -0.1], [-1, 3], [0.1, 0.1]] as [number, number][]) { - const scale = migrate_color_scale(restored.volume, range)! - assert.deepEqual(scale, legacy_color_scale('interpolateTransFlag', range)) - const resolved = { ...restored.volume, colorScale: scale } - assert.equal(migrate_color_scale(resolved, [-1, 1]), scale, 'later automatic range changes must not move migrated points') - } - assert.equal(migrate_color_scale({ colormap: 'interpolateTransFlag' }), undefined) - assert.deepEqual(migrate_color_scale({ colormap: 'interpolateTransFlag', color_range: [-1, 3] }), legacy_color_scale('interpolateTransFlag', [-1, 3])) - const explicit = preset_color_scale('interpolateTransFlag') - assert.equal(migrate_color_scale({ colormap: 'interpolateTransFlag', colorScale: explicit }, [0.1, 0.4]), explicit, 'explicit user scales stay unchanged') -}) - -test('surface buffers and rendered legend share custom stops, midpoint, fallback and linear RGB conversion', async () => { - const server = await createServer({ appType: 'custom', server: { middlewareMode: true, hmr: false, watch: null } }) - try { - const { scalars_to_vertex_colors } = await server.ssrLoadModule('/node_modules/matterviz/dist/isosurface/coloring.js') - const { default: Legend } = await server.ssrLoadModule('/src/EspLegend.svelte') - const { render } = await server.ssrLoadModule('svelte/server') - const values = new Float64Array([-4, -2, 0, 1, 4, 10, NaN]), out = new Float32Array(values.length * 3) - const scale = [{ position: 0, color: '#000000' }, { position: 0.25, color: '#ffffff' }, { position: 1, color: '#ff0000' }] - const result = scalars_to_vertex_colors(values, { colormap: 'interpolateTransFlag', color_stops: scale, color_range: [-2, 6], fallback_color: '#123456' }, out) - assert.equal(result, out, 'recoloring reuses the GPU-bound allocation') - const expected = [[0, 0, 0], [0, 0, 0], [1, 1, 1], [1, 5 / 6, 5 / 6], [1, 1 / 3, 1 / 3], [1, 0, 0]] - const fallback = new Color('#123456') - expected.map(channels => new Color().setRGB(...channels as [number, number, number], SRGBColorSpace).toArray()).concat([fallback.toArray()]) - .flat().forEach((channel, i) => assert.ok(Math.abs(result[i] - channel) < 1e-6, `linear RGB component ${i}`)) - const html = render(Legend, { props: { min: -2, max: 6, color_stops: scale } }).body - assert.ok(html.includes(color_stops_gradient(scale, 'to top'))) - const constant = scalars_to_vertex_colors(new Float64Array([-1, 0, 1]), { color_stops: scale, color_range: [0, 0] }) - const midpoint = new Color().setRGB(1, 2 / 3, 2 / 3, SRGBColorSpace).toArray() - Array.from(constant).forEach((channel, i) => assert.ok(Math.abs(channel - midpoint[i % 3]) < 1e-6)) - assert.ok(render(Legend, { props: { min: 0, max: 0, color_stops: scale } }).body.includes('background: #ffaaaa')) - } finally { await server.close() } -}) diff --git a/frontend/matterviz-viewer/tests/esp-legend.test.ts b/frontend/matterviz-viewer/tests/esp-legend.test.ts deleted file mode 100644 index 1337a29a..00000000 --- a/frontend/matterviz-viewer/tests/esp-legend.test.ts +++ /dev/null @@ -1,34 +0,0 @@ -import assert from 'node:assert/strict' -import { realpathSync } from 'node:fs' -import { createRequire } from 'node:module' -import test from 'node:test' -import { createServer } from 'vite' - -test('rendered ESP legend uses each palette midpoint for zero-width color ranges', async () => { - const server = await createServer({ appType: 'custom', server: { middlewareMode: true, hmr: false, watch: null } }) - try { - const { default: Legend } = await server.ssrLoadModule('/src/EspLegend.svelte') - const { render } = await server.ssrLoadModule('svelte/server') - const { get_d3_interpolator } = await server.ssrLoadModule('/node_modules/matterviz/dist/colors/index.js') - const { scalars_to_vertex_colors } = await server.ssrLoadModule('/node_modules/matterviz/dist/isosurface/coloring.js') - const { Color } = createRequire(realpathSync(new URL('../node_modules/matterviz/dist/isosurface/coloring.js', import.meta.url)))('three') - for (const colormap of ['interpolateViridis', 'interpolateTurbo', 'interpolateCool', 'interpolateTransFlag']) { - const expected = get_d3_interpolator(colormap)(0.5) - const linear = new Color(expected) - for (const endpoint of [-0.05, 0, 0.05]) { - const html = render(Legend, { props: { min: endpoint, max: endpoint, colormap } }).body - assert.ok(html.includes(`background: ${expected}`), `${colormap} at ${endpoint}: expected ${expected}`) - assert.ok(!html.includes('NaN')) - const colors = scalars_to_vertex_colors(new Float64Array([-1, endpoint, 1]), { - colormap, color_range: [endpoint, endpoint], - }) - for (let index = 0; index < 3; index++) { - for (const [channel, value] of [linear.r, linear.g, linear.b].entries()) { - // Surface colors use a 256-entry LUT; the CSS strip samples D3 directly. - assert.ok(Math.abs(colors[index * 3 + channel] - value) < 0.01, `${colormap} surface midpoint`) - } - } - } - } - } finally { await server.close() } -}) diff --git a/frontend/matterviz-viewer/tests/esp-units.test.ts b/frontend/matterviz-viewer/tests/esp-units.test.ts index 519124cb..4bd29d3b 100644 --- a/frontend/matterviz-viewer/tests/esp-units.test.ts +++ b/frontend/matterviz-viewer/tests/esp-units.test.ts @@ -20,8 +20,7 @@ ${values.join(' ')} const close = (actual: number, expected: number): void => { assert.ok(Math.abs(actual - expected) < 1e-10, `${actual} != ${expected}`) } -const values = (volume: VolumetricData): number[] => Array.isArray(volume.grid) - ? volume.grid.flat(2) : Array.from(volume.grid.data) +const values = (volume: VolumetricData): number[] => Array.from(volume.values) test('kcal/mol Cube imports match a.u. values, color range and numerical legend', async () => { const server = await createServer({ appType: 'custom', logLevel: 'silent', server: { middlewareMode: true, hmr: false, watch: null } }) @@ -50,10 +49,6 @@ test('kcal/mol Cube imports match a.u. values, color range and numerical legend' DEFAULT_ESP_LIMIT * KCAL_PER_HARTREE) assert.equal(normalized.origin, original.origin) assert.equal(normalized.lattice, original.lattice) - // The same import adapter also accepts the parser's packed representation. - const packed = { ...original, grid: { dimensions: [2, 2, 2] as [number, number, number], order: 'z-fastest' as const, data: new Float64Array(samples) } } - values(normalize_esp_volume(packed, entry)).forEach((value, index) => close(value, values(atomic)[index])) - assert.deepEqual(Array.from(packed.grid.data), samples) for (const unconverted of [ { ...entry, valueUnit: 'au' as const }, { ...entry, valueUnit: undefined }, diff --git a/frontend/matterviz-viewer/tests/frequency.test.ts b/frontend/matterviz-viewer/tests/frequency.test.ts index 8be8da25..38f2a218 100644 --- a/frontend/matterviz-viewer/tests/frequency.test.ts +++ b/frontend/matterviz-viewer/tests/frequency.test.ts @@ -4,13 +4,15 @@ import test from 'node:test' import { createServer } from 'vite' let server: Awaited> +let upstream: typeof import('matterviz/trajectory') let api: typeof import('../src/frequency.ts') const fixture = async (name = 'gaussian16-water') => JSON.parse(await readFile(new URL(`./fixtures/frequency/${name}.cjson`, import.meta.url), 'utf8')) test.before(async () => { server = await createServer({ - server: { middlewareMode: true, hmr: false }, appType: 'custom', + server: { middlewareMode: true, hmr: false, watch: null }, appType: 'custom', cacheDir: 'node_modules/.vite-frequency-tests', }) + upstream = await server.ssrLoadModule('matterviz/trajectory') api = await server.ssrLoadModule('/src/frequency.ts') }) test.after(async () => { await server?.close() }) @@ -40,8 +42,8 @@ test('real water mode retains O/H displacement ratios and gives a bounded visual assert.deepEqual(data.structure.sites.map(site => site.species[0].element), ['O', 'H', 'H']) const unchanged = JSON.stringify(data) const trajectory = api.frequency_trajectory(data, 0, .35) - assert.equal(trajectory.frames.length, 1, 'only equilibrium is eager; native trajectory owns playback/cache') - const read = async (index: number) => (await trajectory.frame_loader!.load_frame('', index))! + assert.equal(trajectory.frame_count, 48) + const read = async (index: number) => upstream.materialize_frame(await trajectory.read_frame(index)) assert.deepEqual((await read(0)).structure.sites.map(site => site.xyz), data.structure.sites.map(site => site.xyz)) const plus = await read(12), minus = await read(36) const shifts = plus.structure.sites.map((site, atom) => site.xyz.map((v, axis) => v - data.structure.sites[atom].xyz[axis])) @@ -51,7 +53,7 @@ test('real water mode retains O/H displacement ratios and gives a bounded visual for (const [atom, site] of minus.structure.sites.entries()) { site.xyz.forEach((value, axis) => assert.ok(Math.abs(value - data.structure.sites[atom].xyz[axis] + shifts[atom][axis]) < 1e-12)) } - assert.equal(plus.structure.properties?.bonds, data.structure.properties?.bonds, 'equilibrium bonds remain fixed') + assert.deepEqual(plus.structure.properties?.bonds, data.structure.properties?.bonds, 'equilibrium bonds remain fixed') assert.equal(JSON.stringify(data), unchanged) }) @@ -98,7 +100,7 @@ test('invalid visual settings and out-of-range frame access are rejected', async for (const amplitude of [0, -1, NaN, Infinity, 2.01]) assert.throws(() => api.frequency_trajectory(data, 0, amplitude), /amplitude/) assert.throws(() => api.frequency_trajectory(data, 99), /normal mode/) const trajectory = api.frequency_trajectory(data, 0) - for (const frame of [-1, .5, 48, NaN]) await assert.rejects(trajectory.frame_loader!.load_frame('', frame), /frame/) + for (const frame of [-1, .5, 48, NaN]) await assert.rejects(async () => trajectory.read_frame(frame), /frame/i) }) test('tiny finite displacement scales never create NaN coordinates', async () => { @@ -107,7 +109,7 @@ test('tiny finite displacement scales never create NaN coordinates', async () => const data = api.read_frequency_cjson(JSON.stringify(source)) const trajectory = api.frequency_trajectory(data, 0) for (const index of [0, 12]) { - const frame = await trajectory.frame_loader!.load_frame('', index) + const frame = upstream.materialize_frame(await trajectory.read_frame(index)) assert.ok(frame!.structure.sites.every(site => site.xyz.every(Number.isFinite))) } }) diff --git a/frontend/matterviz-viewer/tests/lighting.test.ts b/frontend/matterviz-viewer/tests/lighting.test.ts deleted file mode 100644 index e26f2137..00000000 --- a/frontend/matterviz-viewer/tests/lighting.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -import assert from 'node:assert/strict' -import { readFile } from 'node:fs/promises' -import test from 'node:test' -import ts from 'typescript' -import { createServer } from 'vite' -import { LIGHTING_DEFAULTS, normalize_light_intensity, normalize_lighting } from '../src/lighting.ts' -import { create_workbench_state, parse_workbench_state, restore_workbench_state } from '../src/state.ts' - -test('lighting normalization preserves zero, accepts legacy names and bounds finite intensities', () => { - assert.deepEqual(LIGHTING_DEFAULTS, { ambient_light: 0.72, directional_light: 1.2 }) - assert.deepEqual(normalize_lighting({ ambientLight: 0, directionalLight: '2.4' }), { ambient_light: 0, directional_light: 2.4 }) - assert.deepEqual(normalize_lighting({ ambient_light: -2, directional_light: 10 }), { ambient_light: 0, directional_light: 4 }) - assert.deepEqual(normalize_lighting({ ambientLight: 0, ambient_light: 2 }), { ambient_light: 0 }) - for (const value of [Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY, '', ' ', 'bad', true, null, []]) { - assert.equal(normalize_light_intensity(value), undefined) - assert.deepEqual(normalize_lighting({ ambient_light: value, directional_light: value }), {}) - } - assert.deepEqual(normalize_lighting({}), {}) -}) - -test('saved lighting reaches the actual App restoration without changing camera or atom styling', async () => { - const app = await readFile(new URL('../src/App.svelte', import.meta.url), 'utf8') - const start = app.indexOf(' if (restored.structureAppearance) {') - const end = app.indexOf(' const slice = restored.slice', start) - assert.ok(start > 0 && end > start) - const restoreBlock = ts.transpileModule(app.slice(start, end), { - compilerOptions: { target: ts.ScriptTarget.ESNext, module: ts.ModuleKind.ESNext }, - }).outputText - const apply = new Function('normalize_lighting', 'restored', 'sceneProps', ` - let showGizmo = true, backgroundColor = '#ffffff', backgroundOpacity = 1; - ${restoreBlock} - return sceneProps; - `) - const original = { - camera_position: [2, 3, 4], camera_up: [0, 0, 1], camera_control_mode: 'arcball', - representation_preset: 'spacefill', atom_radius: 1.4, bond_thickness: 0.08, - ambient_light: 0.72, directional_light: 1.2, - } - for (const intensities of [{ ambient_light: 0, directional_light: 0 }, { ambient_light: 1.25, directional_light: 1.55 }, { ambient_light: 4, directional_light: 4 }]) { - const snapshot = create_workbench_state({ - manifest: {}, entries: [], activeVolume: 0, atomSupercell: '1x1x1', showBoundaryAtoms: true, showUnitCell: false, - isosurfaceSettings: { isovalue: 0.025, opacity: 0.65, material: 'pbr', roughness: 0.48 }, - sceneProps: intensities, - }) - assert.deepEqual(snapshot.structureAppearance, { ambientLight: intensities.ambient_light, directionalLight: intensities.directional_light }) - const parsed = parse_workbench_state(JSON.parse(JSON.stringify(snapshot))) - const restored = restore_workbench_state(parsed, { entries: [], isosurfaceSettings: { isovalue: 0.025, opacity: 0.65 } }) - assert.deepEqual(restored.structureAppearance, snapshot.structureAppearance) - const next = apply(normalize_lighting, restored, original) - assert.deepEqual(next, { ...original, ...intensities }) - assert.equal(next.camera_position, original.camera_position) - assert.equal(next.camera_up, original.camera_up) - assert.equal(restored.isosurfaceSettings.isovalue, 0.025) - assert.equal(restored.isosurfaceSettings.opacity, 0.65) - } - const legacy = apply(normalize_lighting, { structureAppearance: { showGizmo: false } }, original) - assert.equal(legacy.ambient_light, original.ambient_light) - assert.equal(legacy.directional_light, original.directional_light) - assert.equal(original.ambient_light, 0.72) -}) - -test('import and direct restore sanitize lighting while older snapshots retain omitted fields', () => { - const base = { format: 'multiwfn-matterviz-workbench', version: 1, activeVolume: 0, volumes: [], session: {} } - for (const appearance of [ - { ambientLight: -5, directionalLight: 20 }, - { ambient_light: '-5', directional_light: '20' }, - ]) { - const snapshot = { ...base, structureAppearance: appearance } - assert.deepEqual(parse_workbench_state(snapshot).structureAppearance, { ambientLight: 0, directionalLight: 4 }) - assert.deepEqual(restore_workbench_state(snapshot, { entries: [], isosurfaceSettings: {} }).structureAppearance, { ambientLight: 0, directionalLight: 4 }) - } - for (const appearance of [{}, { ambientLight: Number.NaN, directionalLight: Number.POSITIVE_INFINITY }]) { - const snapshot = { ...base, structureAppearance: appearance } - assert.equal(parse_workbench_state(snapshot).structureAppearance, undefined) - assert.equal(restore_workbench_state(snapshot, { entries: [], isosurfaceSettings: {} }).structureAppearance, undefined) - } - const partial = parse_workbench_state({ ...base, structureAppearance: { directionalLight: 0 } }) - assert.deepEqual(partial.structureAppearance, { directionalLight: 0 }) -}) - -test('Inspector lighting displays current renderer defaults and restored values in Structure', async () => { - const server = await createServer({ appType: 'custom', server: { middlewareMode: true, hmr: false, watch: null } }) - try { - const { default: Inspector } = await server.ssrLoadModule('/src/ViewerInspector.svelte') - const { render } = await server.ssrLoadModule('svelte/server') - const show = (scene_props: Record) => render(Inspector, { props: { section: 'structure', scene_props, isosurface_settings: {} } }).body - const defaults = show({}) - assert.match(defaults, /lighting-heading/) - assert.match(defaults, /Ambient[\s\S]*?0\.72/) - assert.match(defaults, /Directional[\s\S]*?1\.20/) - assert.match(defaults, /Reset lighting/) - const restored = show({ ambient_light: 0, directional_light: 2.4 }) - assert.match(restored, /Ambient[\s\S]*?0\.00/) - assert.match(restored, /Directional[\s\S]*?2\.40/) - } finally { await server.close() } -}) diff --git a/frontend/matterviz-viewer/tests/material.test.ts b/frontend/matterviz-viewer/tests/material.test.ts deleted file mode 100644 index 30df537a..00000000 --- a/frontend/matterviz-viewer/tests/material.test.ts +++ /dev/null @@ -1,180 +0,0 @@ -import assert from 'node:assert/strict' -import test from 'node:test' -import { - apply_surface_preset, - detect_surface_preset, - normalize_surface_appearance, - normalize_surface_number, - SURFACE_PRESETS, - type SurfacePreset, -} from '../src/material.ts' -import { create_workbench_state, parse_workbench_state, restore_workbench_state } from '../src/state.ts' - -// Original MaterialPanel PRESETS from commit 861d59be68be7efc568f919fcdc5e2c7466e14e2. -// Keep this independent fixture so changing or dropping a legacy combination is visible. -const ORIGINAL_PRESETS = { - Matte: { material: 'matte', outline: 0, outlineWidth: 0.6, transmode: 0 }, - Diffuse: { material: 'matte', outline: 0, outlineWidth: 0.6, transmode: 0 }, - Goodsell: { material: 'matte', roughness: 0.7, metalness: 0, shininess: 18, specular: 0.12, outline: 0, outlineWidth: 0.6, transmode: 0 }, - Edgy: { material: 'glossy', shininess: 50, specular: 0.5, outline: 0.5, outlineWidth: 0.9, transmode: 0 }, - EdgyShiny: { material: 'glossy', shininess: 70, specular: 0.85, outline: 0.6, outlineWidth: 0.92, transmode: 0 }, - AOShiny: { material: 'glossy', shininess: 45, specular: 0.55, outline: 0.15, outlineWidth: 0.7, transmode: 0 }, - AOChalky: { material: 'glossy', shininess: 20, specular: 0.2, outline: 0.1, outlineWidth: 0.6, transmode: 0 }, - Glass1: { material: 'glossy', shininess: 55, specular: 0.65, outline: 0.05, outlineWidth: 0.6, transmode: 1 }, - GlassBubble: { material: 'glossy', shininess: 90, specular: 0.95, outline: 0.05, outlineWidth: 0.6, transmode: 1 }, - EdgyGlass: { material: 'glossy', shininess: 70, specular: 0.6, outline: 0.5, outlineWidth: 0.9, transmode: 1 }, - BrushedMetal: { material: 'pbr', metalness: 0.75, roughness: 0.35, specular: 0.3, outline: 0.05, outlineWidth: 0.6, transmode: 0 }, - Metallic: { material: 'pbr', metalness: 0.8, roughness: 0.28, specular: 0.3, outline: 0.05, outlineWidth: 0.6, transmode: 0 }, - PBR: { material: 'pbr', metalness: 0.2, roughness: 0.5, specular: 0.2, outline: 0.15, outlineWidth: 0.6, transmode: 0 }, - Unlit: { material: 'unlit', outline: 0, outlineWidth: 0.6, transmode: 0 }, -} as const - -const effective_preset = (preset: SurfacePreset): SurfacePreset => - preset === 'diffuse' || preset === 'goodsell' ? 'matte' : preset - -const settings = { - isovalue: 0.045, - opacity: 0.7, - positive_color: '#3177ba', - negative_color: '#ce5588', - show_negative: true, - wireframe: true, - flat_shading: true, - halo: 0.2, - outline: 0.5, - outlineWidth: 0.4, - transmode: 1, - display_range: [[-0.2, 1.3], [0, 1], [0, 1]], - geometry_memory_budget_bytes: 1024, - layers: [{ - volume_idx: 0, - isovalue: 0.013, - opacity: 0.45, - color: '#2c70a2', - negative_color: '#ab538f', - visible: true, - show_negative: true, - color_volume_idx: 1, - colormap: 'interpolateTransFlag', - color_range: [-0.05, 0.05], - }], -} - -test('surface presets preserve scientific settings, colors, and geometry references', () => { - const original = structuredClone(settings) - for (const preset of SURFACE_PRESETS) { - const next = apply_surface_preset(settings, preset.value) - assert.equal(detect_surface_preset(next), effective_preset(preset.value)) - for (const key of ['isovalue', 'opacity', 'positive_color', 'negative_color', 'show_negative', 'halo', 'geometry_memory_budget_bytes'] as const) { - assert.equal(next[key], settings[key], `${preset.value}: ${key}`) - } - assert.equal(next.layers, settings.layers) - assert.equal(next.display_range, settings.display_range) - assert.equal(next.wireframe, false) - assert.equal(next.flat_shading, false) - assert.equal(next.outline, preset.appearance.outline) - assert.equal(next.transmode, preset.appearance.transmode) - } - assert.deepEqual(settings, original) -}) - -test('all original MaterialPanel combinations retain every original parameter and name', () => { - assert.deepEqual(SURFACE_PRESETS.filter((preset) => !preset.group).map((preset) => preset.value), ['matte', 'soft-gloss', 'satin', 'unlit']) - const legacyNames = Object.keys(ORIGINAL_PRESETS).filter((name) => name !== 'Matte' && name !== 'Unlit') - assert.deepEqual(SURFACE_PRESETS.filter((preset) => preset.group === 'legacy').map((preset) => preset.label), legacyNames) - assert.equal(new Set(SURFACE_PRESETS.map((preset) => preset.value)).size, SURFACE_PRESETS.length) - for (const [name, original] of Object.entries(ORIGINAL_PRESETS)) { - const preset = SURFACE_PRESETS.find((item) => name === 'Unlit' ? item.value === 'unlit' : item.label === name) - assert.ok(preset, name) - assert.deepEqual(preset.appearance, { wireframe: false, flat_shading: false, ...original }, name) - const next = apply_surface_preset(settings, preset.value) - for (const [key, value] of Object.entries(original)) assert.equal(next[key], value, `${name}: ${key}`) - } -}) - -test('preset selection follows active renderer values after manual refinement', () => { - assert.equal(detect_surface_preset({}), 'matte') - const satin = apply_surface_preset(settings, 'satin') - assert.equal(detect_surface_preset({ ...satin, shininess: 117, specular: 0.9 }), 'satin') - assert.equal(detect_surface_preset({ ...satin, roughness: 0.5 }), 'custom') - assert.equal(detect_surface_preset({ ...satin, flat_shading: true }), 'custom') - assert.equal(detect_surface_preset({ ...satin, wireframe: true }), 'custom') - assert.equal(detect_surface_preset({ ...satin, outline: 0.2 }), 'custom') - assert.equal(detect_surface_preset({ ...satin, outlineWidth: 0.1 }), 'satin') - const unlit = apply_surface_preset(settings, 'unlit') - assert.equal(detect_surface_preset({ ...unlit, outline: 1, flat_shading: true, transmode: 1 }), 'unlit') -}) - -test('legacy detection ignores inactive parameters and canonicalizes equivalent matte finishes', () => { - for (const name of ['diffuse', 'goodsell'] as const) { - const matte = apply_surface_preset(settings, name) - assert.equal(detect_surface_preset({ ...matte, roughness: 0.12, metalness: 0.9, shininess: 119, specular: 0.99 }), 'matte') - } - for (const name of ['brushed-metal', 'metallic', 'pbr'] as const) { - const pbr = apply_surface_preset(settings, name) - assert.equal(detect_surface_preset({ ...pbr, shininess: 117, specular: 0.91 }), name) - assert.equal(detect_surface_preset({ ...pbr, roughness: 0.91 }), 'custom') - } - for (const preset of SURFACE_PRESETS.filter((item) => item.group === 'legacy' && item.appearance.material === 'glossy')) { - const glossy = apply_surface_preset(settings, preset.value) - assert.equal(detect_surface_preset({ ...glossy, roughness: 0.91, metalness: 0.92 }), preset.value) - assert.equal(detect_surface_preset({ ...glossy, shininess: 119 }), 'custom') - } -}) - -test('appearance normalization rejects nonfinite data and clamps renderer limits', () => { - assert.deepEqual(normalize_surface_appearance({ - material: 'unlit', wireframe: false, flat_shading: true, - roughness: -2, metalness: 9, shininess: '999', specular: '-4', halo: '2', - outline: 2, outlineWidth: -1, transmode: 1, - layers: settings.layers, isovalue: 4, - }), { - material: 'unlit', wireframe: false, flat_shading: true, - roughness: 0, metalness: 1, shininess: 120, specular: 0, halo: 1, - outline: 1, outlineWidth: 0, transmode: 1, - }) - assert.deepEqual(normalize_surface_appearance({ - material: 'unknown', wireframe: 'true', flat_shading: 1, - roughness: Number.NaN, metalness: Number.POSITIVE_INFINITY, - shininess: Number.NEGATIVE_INFINITY, specular: '', halo: null, - outline: true, outlineWidth: [], transmode: 2, - }), {}) - assert.equal(normalize_surface_number('shininess', -10), 1) - assert.equal(normalize_surface_number('roughness', ' '), undefined) -}) - -test('every finish survives JSON save and restore with camera and layer styling intact', () => { - const camera = { position: [1, 2, 3], target: [0.2, 0.3, 0.4], up: [0.1, 0.9, 0.2], zoom: 1.4, projection: 'orthographic' } - const entries = [{ path: 'density.cube' }, { path: 'esp.cube' }] - for (const preset of SURFACE_PRESETS) { - const styled = apply_surface_preset(settings, preset.value) - const snapshot = create_workbench_state({ - manifest: {}, entries, isosurfaceSettings: styled, activeVolume: 1, - atomSupercell: '1x1x1', showBoundaryAtoms: true, showUnitCell: false, camera, - }) - const parsed = parse_workbench_state(JSON.parse(JSON.stringify(snapshot))) - const restored = restore_workbench_state(parsed, { entries, isosurfaceSettings: settings }) - assert.equal(detect_surface_preset(restored.isosurfaceSettings), effective_preset(preset.value)) - assert.deepEqual(normalize_surface_appearance(restored.isosurfaceSettings), normalize_surface_appearance(styled)) - assert.deepEqual(restored.camera, camera) - assert.deepEqual(restored.isosurfaceSettings.layers, settings.layers) - assert.equal(restored.isosurfaceSettings.halo, settings.halo) - assert.equal(restored.isosurfaceSettings.flat_shading, false) - assert.equal(restored.activeVolume, 1) - } -}) - -test('legacy workbench snapshots restore material combinations without storing preset markers', () => { - for (const [name, appearance] of Object.entries(ORIGINAL_PRESETS)) { - const preset = SURFACE_PRESETS.find((item) => name === 'Unlit' ? item.value === 'unlit' : item.label === name)! - const parsed = parse_workbench_state({ - format: 'multiwfn-matterviz-workbench', version: 1, activeVolume: 0, volumes: [], session: {}, - isosurface: { ...appearance, wireframe: false, flatShading: false }, - }) - const restored = restore_workbench_state(parsed, { entries: [], isosurfaceSettings: settings }) - assert.equal(detect_surface_preset(restored.isosurfaceSettings), effective_preset(preset.value), name) - for (const [key, value] of Object.entries(appearance)) assert.equal(restored.isosurfaceSettings[key], value, `${name}: ${key}`) - assert.equal('preset' in parsed.isosurface!, false) - assert.equal('preset' in restored.isosurfaceSettings, false) - } -}) diff --git a/frontend/matterviz-viewer/tests/matterviz-measure.test.ts b/frontend/matterviz-viewer/tests/matterviz-measure.test.ts deleted file mode 100644 index 582363c2..00000000 --- a/frontend/matterviz-viewer/tests/matterviz-measure.test.ts +++ /dev/null @@ -1,133 +0,0 @@ -import assert from 'node:assert/strict' -import test from 'node:test' -import { createServer } from 'vite' - -const close_to = (actual: number | null, expected: number, tolerance = 1e-10): void => { - assert.notEqual(actual, null) - assert.ok( - Math.abs((actual as number) - expected) <= tolerance, - `expected ${String(actual)} to be within ${tolerance} of ${expected}`, - ) -} - -test('vendored measurement helpers implement ordered Multiwfn interactions', async (context) => { - const vite = await createServer({ - configFile: false, - server: { middlewareMode: true, watch: null, hmr: false }, - appType: 'custom', - optimizeDeps: { noDiscovery: true }, - }) - - try { - const measure = await vite.ssrLoadModule('/node_modules/matterviz/dist/structure/measure.js') - - await context.test('distance restarts after two sites and selecting a chosen site cancels it', () => { - const distanceRule = measure.resolve_measure_selection_rule({ - distance: { max_sites: 2, overflow: 'restart' }, - angle: { max_sites: 4, overflow: 'reject' }, - }, 'distance') - - assert.deepEqual(distanceRule, { max_sites: 2, overflow: 'restart' }) - assert.deepEqual(measure.next_measured_sites([], 4, distanceRule), { - sites: [4], - limit_reached: false, - }) - assert.deepEqual(measure.next_measured_sites([4], 7, distanceRule), { - sites: [4, 7], - limit_reached: false, - }) - assert.deepEqual(measure.next_measured_sites([4, 7], 9, distanceRule), { - sites: [9], - limit_reached: false, - }) - assert.deepEqual(measure.next_measured_sites([4, 7], 4, distanceRule), { - sites: [7], - limit_reached: false, - }) - }) - - await context.test('angle keeps four ordered sites and rejects a fifth', () => { - const policy = { - distance: { max_sites: 2, overflow: 'restart' }, - angle: { max_sites: 4, overflow: 'reject' }, - } - const angleRule = measure.resolve_measure_selection_rule(policy, 'angle') - const distanceRule = measure.resolve_measure_selection_rule(policy, 'distance') - - assert.deepEqual(angleRule, { max_sites: 4, overflow: 'reject' }) - assert.notDeepEqual(angleRule, distanceRule) - assert.deepEqual(measure.next_measured_sites([0, 1, 2], 3, angleRule), { - sites: [0, 1, 2, 3], - limit_reached: false, - }) - const fullSelection = [0, 1, 2, 3] - const rejected = measure.next_measured_sites(fullSelection, 4, angleRule) - assert.deepEqual(rejected, { - sites: [0, 1, 2, 3], - limit_reached: true, - }) - assert.deepEqual(fullSelection, [0, 1, 2, 3]) - assert.notStrictEqual(rejected.sites, fullSelection) - }) - - await context.test('displayed PBC endpoints only match within a finite position tolerance', () => { - assert.equal(measure.positions_match([0, 0, 0], [0, 0, 0]), true) - assert.equal(measure.positions_match([0, 0, 0], [5e-7, 0, 0]), true) - assert.equal(measure.positions_match([0, 0, 0], [2e-6, 0, 0]), false) - assert.equal(measure.positions_match([0, 0, 0], [10, 0, 0]), false) - assert.equal(measure.positions_match([0, 0, 0], [Number.NaN, 0, 0]), false) - }) - - await context.test('ordered bond angles use the middle site and minimum-image vectors', () => { - close_to( - measure.bond_angle([1, 0, 0], [0, 0, 0], [0, 1, 0]), - 90, - ) - - const lattice = [[10, 0, 0], [0, 10, 0], [0, 0, 10]] - close_to( - measure.bond_angle([9.5, 0, 0], [0.5, 0, 0], [0.5, 1, 0], lattice), - 90, - ) - }) - - await context.test('signed dihedrals cover both orientations and the 180-degree boundary', () => { - const a = [0, 1, 0] - const b = [0, 0, 0] - const c = [1, 0, 0] - - close_to(measure.dihedral_angle(a, b, c, [1, 0, -1]), -90) - close_to(measure.dihedral_angle(a, b, c, [1, 0, 1]), 90) - close_to(Math.abs(measure.dihedral_angle(a, b, c, [1, -1, 0])), 180) - }) - - await context.test('dihedral geometry follows the minimum-image chain under PBC', () => { - const lattice = [[10, 0, 0], [0, 10, 0], [0, 0, 10]] - const angle = measure.dihedral_angle( - [9.5, 1, 0], - [9.5, 0, 0], - [0.5, 0, 0], - [0.5, 0, 1], - lattice, - ) - close_to(angle, 90) - }) - - await context.test('degenerate angles return null instead of a non-finite value', () => { - assert.equal( - measure.bond_angle([0, 0, 0], [0, 0, 0], [0, 1, 0]), - null, - ) - assert.equal( - measure.dihedral_angle([0, 0, 0], [0, 0, 0], [1, 0, 0], [1, 1, 0]), - null, - ) - assert.equal( - measure.dihedral_angle([0, 0, 0], [1, 0, 0], [2, 0, 0], [2, 1, 0]), - null, - ) - }) - } finally { - await vite.close() - } -}) diff --git a/frontend/matterviz-viewer/tests/native-structure.test.ts b/frontend/matterviz-viewer/tests/native-structure.test.ts index 34003194..f7bb4f68 100644 --- a/frontend/matterviz-viewer/tests/native-structure.test.ts +++ b/frontend/matterviz-viewer/tests/native-structure.test.ts @@ -5,12 +5,12 @@ import { createServer, type ViteDevServer } from 'vite' import type { AnyStructure } from 'matterviz' let server: ViteDevServer -let parse_any_structure: (content: string, filename: string) => AnyStructure +let parse_structure_file: (content: string, filename: string) => AnyStructure test.before(async () => { - server = await createServer({ appType: 'custom', logLevel: 'silent', server: { middlewareMode: true } }) + server = await createServer({ appType: 'custom', logLevel: 'silent', server: { middlewareMode: true, watch: null, hmr: false } }) const parser = await server.ssrLoadModule('matterviz/structure/parse') - parse_any_structure = parser.parse_any_structure + parse_structure_file = parser.parse_structure_file }) test.after(async () => { @@ -55,7 +55,7 @@ test('parses native nonperiodic JSON and preserves explicit root bond orders', ( properties: { bonds }, } - const parsed = parse_any_structure(JSON.stringify(native), 'structure.json') + const parsed = parse_structure_file(JSON.stringify(native), 'structure.json') assert.equal(parsed.charge, 0) assert.equal('lattice' in parsed, false) @@ -79,7 +79,7 @@ test('parses native periodic JSON and round-trips the lattice matrix', () => { }, } - const parsed = parse_any_structure(JSON.stringify(native), 'structure.json') + const parsed = parse_structure_file(JSON.stringify(native), 'structure.json') assert.ok('lattice' in parsed && parsed.lattice) assert.deepEqual(parsed.lattice.matrix, native.lattice.matrix) @@ -95,7 +95,7 @@ test('parses native periodic JSON and round-trips the lattice matrix', () => { test('preserves explicit cross-boundary bond cell shifts from a native periodic artifact', async () => { const artifact = new URL('./artifacts/periodic-cross-boundary/structure.json', import.meta.url) - const parsed = parse_any_structure(await readFile(artifact, 'utf8'), 'structure.json') + const parsed = parse_structure_file(await readFile(artifact, 'utf8'), 'structure.json') assert.ok('lattice' in parsed && parsed.lattice) assert.deepEqual(parsed.lattice.matrix, [[5, 0, 0], [1, 4, 0], [0.5, 0.25, 5]]) @@ -107,7 +107,7 @@ test('preserves explicit cross-boundary bond cell shifts from a native periodic }]) }) -test('preserves a labeled Multiwfn ghost center without mapping it to a real element', () => { +test('reports a Multiwfn ghost center as an unsupported species', () => { const native = { sites: [{ species: [{ element: 'Bq', occu: 1, oxidation_state: 0 }], @@ -120,9 +120,5 @@ test('preserves a labeled Multiwfn ghost center without mapping it to a real ele properties: { bonds: [] }, } - const parsed = parse_any_structure(JSON.stringify(native), 'structure.json') - - assert.equal(parsed.sites[0]?.species[0]?.element, 'Bq') - assert.equal(parsed.sites[0]?.properties?.multiwfnGhost, true) - assert.deepEqual(parsed.sites[0]?.xyz, [1, 2, 3]) + assert.throws(() => parse_structure_file(JSON.stringify(native), 'structure.json'), /Bq is not an element/) }) diff --git a/frontend/matterviz-viewer/tests/periodic.test.ts b/frontend/matterviz-viewer/tests/periodic.test.ts index 3dfb0938..d6a47fb5 100644 --- a/frontend/matterviz-viewer/tests/periodic.test.ts +++ b/frontend/matterviz-viewer/tests/periodic.test.ts @@ -5,12 +5,6 @@ import { inject_manifest_lattice, supercell_scaling_for_ranges, } from '../src/periodic.ts' -import { display_range } from '../src/manifest.ts' -import { - create_workbench_state, - parse_workbench_state, - restore_workbench_state, -} from '../src/state.ts' test('clamps periodic range inputs and rejects missing or non-finite values', () => { assert.equal(clamp_periodic_bound(-50), -20) @@ -114,43 +108,6 @@ test('maps fractional and negative ranges to integer atom supercells', () => { ) }) -test('keeps fractional display ranges independent from persisted atom supercell settings', () => { - const manifest = { - periodic: { - enabled: true, - ranges: { - a: [-1.25, 2.75], - b: [0.125, 1.875], - c: [-0.5, 0.5], - }, - }, - } - const ranges = display_range(manifest) - assert.deepEqual(ranges, [[-1.25, 2.75], [0.125, 1.875], [-0.5, 0.5]]) - assert.equal(supercell_scaling_for_ranges(ranges), '5x2x2') - - const exported = create_workbench_state({ - manifest, - entries: [{ path: 'density.cube' }], - isosurfaceSettings: { display_range: ranges }, - activeVolume: 0, - atomSupercell: '1x1x1', - showBoundaryAtoms: true, - showUnitCell: false, - }) - assert.deepEqual(exported.periodic, { - displayRange: ranges, - atomSupercell: '1x1x1', - showBoundaryAtoms: true, - showUnitCell: false, - }) - - const restored = restore_workbench_state(parse_workbench_state(exported), { - entries: [{ path: 'density.cube' }], - isosurfaceSettings: {}, - }) - assert.deepEqual(restored.periodic, exported.periodic) -}) test('preserves cross-boundary bond cell-shift metadata for MatterViz', () => { const structure = inject_manifest_lattice( diff --git a/frontend/matterviz-viewer/tests/plot-v2.test.ts b/frontend/matterviz-viewer/tests/plot-v2.test.ts index eb8a05a5..7a21868c 100644 --- a/frontend/matterviz-viewer/tests/plot-v2.test.ts +++ b/frontend/matterviz-viewer/tests/plot-v2.test.ts @@ -71,7 +71,7 @@ test('parses v2 layers, explicit axes, reversed/log ranges, and annotations', () }) test('compiles the v2 component entry with lazy v1 initialization', async () => { - const server = await createServer({ appType: 'custom', server: { middlewareMode: true } }) + const server = await createServer({ appType: 'custom', server: { middlewareMode: true, watch: null, hmr: false } }) try { const module = await server.ssrLoadModule('/src/MultiwfnPlotView.svelte') assert.equal(typeof module.default, 'function') diff --git a/frontend/matterviz-viewer/tests/representation.test.ts b/frontend/matterviz-viewer/tests/representation.test.ts deleted file mode 100644 index bb767cb3..00000000 --- a/frontend/matterviz-viewer/tests/representation.test.ts +++ /dev/null @@ -1,135 +0,0 @@ -import assert from 'node:assert/strict' -import test from 'node:test' -import { - apply_representation_preset, - detect_representation_preset, - refine_representation, -} from '../src/representation.ts' - -test('maps all original GUI representation presets atomically', () => { - const base = { atom_radius: 1.2, bond_thickness: 0.3, same_size_atoms: true } - assert.deepEqual( - apply_representation_preset(base, 'ballstick'), - { - ...base, - representation_preset: 'ballstick', - representation_atom_base: 1.2, - representation_bond_base: 0.3, - show_atoms: true, - show_bonds: 'always', - atom_radius: 1.2, - same_size_atoms: false, - bond_thickness: 0.3, - }, - ) - assert.deepEqual( - apply_representation_preset(base, 'spacefill'), - { - ...base, - representation_preset: 'spacefill', - representation_atom_base: 1.2, - representation_bond_base: 0.3, - show_atoms: true, - show_bonds: 'never', - atom_radius: 2.22, - same_size_atoms: false, - bond_thickness: 0.3, - }, - ) - assert.deepEqual( - apply_representation_preset(base, 'stick'), - { - ...base, - representation_preset: 'stick', - representation_atom_base: 1.2, - representation_bond_base: 0.3, - show_atoms: false, - show_bonds: 'always', - atom_radius: 1.2, - same_size_atoms: false, - bond_thickness: 0.354, - }, - ) - assert.deepEqual( - apply_representation_preset(base, 'wire'), - { - ...base, - representation_preset: 'wire', - representation_atom_base: 1.2, - representation_bond_base: 0.3, - show_atoms: false, - show_bonds: 'always', - atom_radius: 1.2, - same_size_atoms: false, - bond_thickness: 0.084, - }, - ) -}) - -test('switching repeatedly does not compound preset ratios', () => { - let scene = { atom_radius: 1.1, bond_thickness: 0.2 } - scene = apply_representation_preset(scene, 'spacefill') - scene = apply_representation_preset(scene, 'ballstick') - scene = apply_representation_preset(scene, 'spacefill') - scene = apply_representation_preset(scene, 'ballstick') - assert.equal(scene.atom_radius, 1.1) - assert.equal(scene.bond_thickness, 0.2) - - scene = apply_representation_preset(scene, 'wire') - scene = apply_representation_preset(scene, 'stick') - scene = apply_representation_preset(scene, 'wire') - assert.equal(scene.bond_thickness, 0.2 * 0.28) -}) - -test('manual transformed refinements become the next preset base', () => { - let scene = apply_representation_preset({ atom_radius: 0.8, bond_thickness: 0.1 }, 'spacefill') - scene = refine_representation(scene, 'atom_radius', 2.4) - scene = apply_representation_preset(scene, 'ballstick') - assert.equal(scene.atom_radius, 2.4 / 1.85) - - scene = apply_representation_preset(scene, 'stick') - scene = refine_representation(scene, 'bond_thickness', 0.5) - scene = apply_representation_preset(scene, 'ballstick') - assert.equal(scene.bond_thickness, 0.5 / 1.18) -}) - -test('preserves bases when preset output dimensions hit clamps', () => { - let scene = apply_representation_preset({ atom_radius: 3, bond_thickness: 0.01 }, 'spacefill') - assert.equal(scene.atom_radius, 3) - scene = apply_representation_preset(scene, 'ballstick') - assert.equal(scene.atom_radius, 3) - - scene = apply_representation_preset(scene, 'wire') - assert.equal(scene.bond_thickness, 0.025) - scene = apply_representation_preset(scene, 'ballstick') - assert.equal(scene.bond_thickness, 0.01) -}) - -test('invalidates stale markers after native topology edits', () => { - const scene = apply_representation_preset({ atom_radius: 1, bond_thickness: 0.2 }, 'spacefill') - const edited = { ...scene, show_atoms: false, show_bonds: 'always' } - assert.equal(detect_representation_preset(edited), 'stick') - assert.equal(apply_representation_preset(edited, 'ballstick').atom_radius, 1.85) -}) - -test('refinement controls update the current preset base without changing topology', () => { - let scene = apply_representation_preset({ atom_radius: 0.8, bond_thickness: 0.1 }, 'spacefill') - scene = refine_representation(scene, 'atom_radius', 2.4) - assert.equal(scene.atom_radius, 2.4) - scene = apply_representation_preset(scene, 'ballstick') - assert.equal(scene.atom_radius, 2.4 / 1.85) - - scene = apply_representation_preset(scene, 'wire') - scene = refine_representation(scene, 'bond_thickness', 0.05) - assert.equal(scene.show_atoms, false) - assert.equal(scene.show_bonds, 'always') - scene = apply_representation_preset(scene, 'ballstick') - assert.equal(scene.bond_thickness, 0.05 / 0.28) -}) - -test('normalizes non-finite and out-of-range dimensions', () => { - const scene = apply_representation_preset({ atom_radius: Number.NaN, bond_thickness: 40 }, 'spacefill') - assert.equal(scene.atom_radius, 1.295) - assert.equal(scene.bond_thickness, 1) - assert.equal(detect_representation_preset({ show_atoms: true, show_bonds: 'never' }), 'spacefill') -}) diff --git a/frontend/matterviz-viewer/tests/reps.test.ts b/frontend/matterviz-viewer/tests/reps.test.ts deleted file mode 100644 index a76195db..00000000 --- a/frontend/matterviz-viewer/tests/reps.test.ts +++ /dev/null @@ -1,258 +0,0 @@ -import assert from 'node:assert/strict' -import test from 'node:test' -import { MeshPhongMaterial, MeshBasicMaterial, ShaderLib, Mesh, SphereGeometry, Raycaster, Vector3, Plane, Box3 } from 'three' -import type { AnyStructure } from 'matterviz/structure' -import { create_rep, copy_rep, normalize_reps, migrate_reps, rep_surface_settings, remap_rep_sources, dataset_source, material_preset, rep_scene_props, type Cell } from '../src/reps.ts' -import { rep_clip_planes, rep_translations, rep_structure, fractional_position, translate_cell, select_rep_sites, clipped_rep_bounds, rep_bonds } from '../src/rep-periodic.ts' -import { update_rep_material, clip_rep_raycast } from '../src/rep-material.ts' -import { create_workbench_state, parse_workbench_state, restore_workbench_state } from '../src/state.ts' - -const source: AnyStructure = { - sites: [ - { xyz: [0.5, 0.5, 0.5], abc: [0.125, 0.125, 0.125], species: [{ element: 'C', occu: 1, oxidation_state: 0 }], label: 'C1', properties: {} }, - { xyz: [1.5, 0.5, 0.5], abc: [0.375, 0.125, 0.125], species: [{ element: 'O', occu: 1, oxidation_state: 0 }], label: 'O2', properties: {} }, - ], properties: { bonds: [{ site_idx_1: 0, site_idx_2: 1, order: 2 }] }, -} -const cubic: Cell = [[4, 0, 0], [0, 4, 0], [0, 0, 4]] - -test('duplicated Reps independently own geometry controls, material, data mapping and PBC', () => { - const first = create_rep({ kind: 'volume', index: 0, path: 'density.cube' }, 'first') - first.volume.color_volume_idx = 1; first.volume.colorSourcePath = 'esp.cube' - const second = copy_rep(first, 'second') - second.material.opacity = 0.3; second.material.shininess = 90 - second.periodic.enabled = true; second.periodic.range[0] = [-0.5, 1.5] - second.volume.isovalue = 0.008; second.volume.color = '#ff0000' - assert.equal(first.material.opacity, 1) - assert.deepEqual(first.periodic.range[0], [0, 1]) - assert.equal(first.volume.isovalue, 0.02) - assert.equal(second.followData, false) - assert.equal(rep_surface_settings(second).layers?.[0].color_volume_idx, 1) - assert.equal(rep_surface_settings(second).layers?.[0].opacity, 0.3) -}) - -test('fractional clipping uses actual skew/reflected vectors and shifted origins', () => { - for (const cell of [cubic, [[4, 0, 0], [1, 3, 0], [0.5, 0.3, 5]], [[-4, 0, 0], [1, 3, 0], [0, 0, 5]]] as Cell[]) { - const rep = create_rep({ kind: 'structure' }, 'pbc') - rep.periodic.enabled = true; rep.periodic.range = [[-0.5, 1.5], [0.25, 1.1], [-0.2, 0.8]] - const origin: [number, number, number] = [2, -1, 3] - const planes = rep_clip_planes(rep.periodic, cell, origin) - for (const frac of [[0, 0.5, 0.5], [-0.6, 0.5, 0.5], [1.6, 0.5, 0.5], [0, 0.2, 0.5], [0, 0.5, 0.9]] as [number, number, number][]) { - const point = new Vector3(...translate_cell(cell, frac)).add(new Vector3(...origin)) - const expected = frac.every((n, axis) => n >= rep.periodic.range[axis][0] && n <= rep.periodic.range[axis][1]) - assert.equal(planes.every((plane) => plane.distanceToPoint(point) >= -1e-8), expected) - const roundTrip = fractional_position(cell, point.toArray(), origin) - roundTrip.forEach((n, axis) => assert.ok(Math.abs(n - frac[axis]) < 1e-12)) - } - } -}) - -test('periodic copies translate in custom vectors, allow noninteger ranges, and bound allocation', () => { - const rep = create_rep({ kind: 'structure' }, 'pbc') - rep.periodic.enabled = true; rep.periodic.range[0] = [-0.5, 1.5] - assert.deepEqual(rep_translations(rep.periodic, cubic), [[-4, 0, 0], [0, 0, 0], [4, 0, 0]]) - rep.periodic.axes[0] = false - assert.deepEqual(rep_translations(rep.periodic, cubic), [[0, 0, 0]]) - assert.equal(rep_clip_planes(rep.periodic, cubic).length, 4) - rep.periodic.axes = [true, true, true]; rep.periodic.range = [[-20, 20], [-20, 20], [-20, 20]] - assert.throws(() => rep_translations(rep.periodic, cubic), /exceeds 512/) - assert.throws(() => rep_clip_planes(rep.periodic, [[1, 0, 0], [2, 0, 0], [0, 0, 1]]), /valid lattice/) -}) - -test('finite structure display retains source positions, atom identities and explicit bond orders', () => { - const original = structuredClone(source), rep = create_rep({ kind: 'structure' }, 'structure') - rep.periodic.enabled = true; rep.periodic.axes = [true, false, false]; rep.periodic.range[0] = [0, 1.5] - rep.periodic.cell = [[5, 1, 0], [0, 4, 0], [0, 0, 4]] - const result = rep_structure(source, rep, cubic) - for (const [index, site] of result.structure.sites.entries()) { - const input = source.sites[result.sourceIndices[index]], translation = translate_cell(rep.periodic.cell, result.shifts[index]) - assert.deepEqual(site.xyz, input.xyz.map((n, axis) => n + translation[axis])) - assert.equal(site.properties.rep_source_index, result.sourceIndices[index]) - } - assert.ok(result.structure.properties?.bonds?.length) - for (const bond of result.structure.properties!.bonds!) { - assert.equal(bond.order, 2) - const [a, b] = [bond.site_idx_1, bond.site_idx_2].map((index) => result.structure.sites[index].xyz) - assert.ok(Math.abs(new Vector3(...a).distanceTo(new Vector3(...b)) - 1) < 1e-12) - } - assert.deepEqual(source, original) -}) - -test('atom selection is explicit and cannot accidentally select a different atom', () => { - assert.deepEqual(select_rep_sites(source, 'all'), [0, 1]) - assert.deepEqual(select_rep_sites(source, 'element O'), [1]) - assert.deepEqual(select_rep_sites(source, 'index 1-2, 2'), [0, 1]) - assert.throws(() => select_rep_sites(source, 'index 0'), /outside/) - assert.throws(() => select_rep_sites(source, 'name protein'), /Use all/) -}) - -test('all independent Reps round trip and remap geometry and color sources by identity', () => { - const first = create_rep({ kind: 'volume', index: 0, path: 'density.cube' }, 'density') - first.volume.color_volume_idx = 1; first.volume.colorSourcePath = 'esp.cube' - first.material.diffuse = 2.4; first.material.saturation = 2.6; first.material.opacity = 0.6 - const second = copy_rep(first, 'copy') - second.material.saturation = 0 - second.periodic.cell = cubic; second.periodic.range[1] = [-0.25, 1.25]; second.periodic.enabled = true - const representations = { items: [first, second], selectedId: 'copy' } - const entries = [{ path: 'density.cube' }, { path: 'esp.cube' }] - const isosurfaceSettings = rep_surface_settings(first) - const state = parse_workbench_state(JSON.parse(JSON.stringify(create_workbench_state({ representations, manifest: {}, entries, isosurfaceSettings, activeVolume: 0, atomSupercell: '1x1x1', showBoundaryAtoms: true, showUnitCell: true })))) - assert.deepEqual(state.representations, normalize_reps(representations)) - const restored = restore_workbench_state(state, { entries: [...entries].reverse(), isosurfaceSettings }).representations! - assert.equal(restored.selectedId, 'copy') - assert.equal(restored.items[0].source.kind === 'volume' && restored.items[0].source.index, 1) - assert.equal(restored.items[0].volume.color_volume_idx, 0) - assert.equal(restored.items[0].material.diffuse, 2.4) - assert.equal(restored.items[0].material.saturation, 2.6) - assert.equal(restored.items[1].material.saturation, 0) - assert.deepEqual(restored.items[1].periodic.range[1], [-0.25, 1.25]) - assert.equal((remap_rep_sources(representations, [{ path: 'unrelated.cube' }]).items[0].source as { index: number }).index, -1) -}) - -test('malformed saved cells and duplicate IDs are rejected instead of silently changing the display', () => { - const rep = create_rep({ kind: 'structure' }, 'same') - assert.throws(() => normalize_reps({ items: [rep, rep], selectedId: rep.id }), /Duplicate/) - rep.periodic.cell = [[1, 0, 0], [2, 0, 0], [0, 0, 1]] - assert.throws(() => normalize_reps({ items: [rep] }), /nonsingular/) -}) - -test('legacy layers migrate with their sign, palette, opacity, material and cross-volume mapping', () => { - const volume = create_rep({ kind: 'volume', index: 0 }, 'legacy') - volume.material.opacity = 0.25; volume.material.outline = 0.7; volume.volume.color_volume_idx = 1; volume.volume.colormap = 'interpolateTransFlag' - const migrated = migrate_reps({ atom_opacity: 0.6, show_bonds: 'never' }, rep_surface_settings(volume), [{ path: 'density' }, { path: 'esp' }], true) - assert.equal(migrated.items[0].structure.style, 'spacefill') - assert.equal(migrated.items[0].material.opacity, 0.6) - assert.equal(migrated.items[1].material.opacity, 0.25) - assert.equal(migrated.items[1].material.outline, 0.7) - assert.equal(migrated.items[1].volume.colorSourcePath, 'esp') -}) - -test('diffuse gain and saturation update live uniforms without rebuilding the material', () => { - const rep = create_rep({ kind: 'structure' }, 'appearance'), material = new MeshPhongMaterial() - update_rep_material(material, rep.material, []) - const shader = { vertexShader: ShaderLib.phong.vertexShader, fragmentShader: ShaderLib.phong.fragmentShader, uniforms: {} } - material.onBeforeCompile(shader, null as never) - assert.match(shader.fragmentShader, /reflectedLight.directDiffuse \*= repDiffuse/) - const uniform = (shader.uniforms as Record).repDiffuse - const saturation = (shader.uniforms as Record).repSaturation - assert.equal(saturation.value, 1) - assert.ok(shader.fragmentShader.indexOf('float repLuminance') > shader.fragmentShader.indexOf('#include ')) - assert.ok(shader.fragmentShader.indexOf('float repLuminance') < shader.fragmentShader.indexOf('#include ')) - const version = material.version - update_rep_material(material, { ...rep.material, diffuse: 3, saturation: 2.5 }, []) - assert.equal(uniform.value, 3) - assert.equal(saturation.value, 2.5) - assert.equal(material.version, version) - material.dispose() - const unlit = new MeshBasicMaterial() - update_rep_material(unlit, { ...rep.material, model: 'unlit', diffuse: 0.2, saturation: 0 }, []) - const basicShader = { vertexShader: ShaderLib.basic.vertexShader, fragmentShader: ShaderLib.basic.fragmentShader, uniforms: {} } - unlit.onBeforeCompile(basicShader, null as never) - assert.equal((basicShader.uniforms as Record).repDiffuse.value, 1, - 'unlit and wireframe colors ignore inactive diffuse controls') - assert.equal((basicShader.uniforms as Record).repSaturation.value, 0, - 'unlit and wireframe still support saturation') - unlit.dispose() -}) - -test('legacy saturation defaults to 1 and gain controls clamp independently from opacity', () => { - const rep = create_rep({ kind: 'structure' }, 'legacy') - const normalize = (material: Record) => normalize_reps({ items: [{ ...rep, material }], selectedId: rep.id })!.items[0].material - assert.equal(normalize({ diffuse: 0.4 }).saturation, 1) - assert.equal(normalize({ diffuse: 0.4 }).diffuse, 0.4) - for (const value of [0, 1, 2.5, 3]) { - const material = normalize({ diffuse: value, saturation: value, opacity: value }) - assert.equal(material.diffuse, value) - assert.equal(material.saturation, value) - assert.equal(material.opacity, Math.min(value, 1)) - } - for (const [value, expected] of [[-4, 0], [8, 3], [Infinity, 1], [NaN, 1], [undefined, 1]] as const) { - const material = normalize({ diffuse: value, saturation: value }) - assert.equal(material.diffuse, expected) - assert.equal(material.saturation, expected) - } - const reset = material_preset({ ...rep.material, diffuse: 2, saturation: 3 }, 'glass1') - assert.equal(reset.diffuse, 1); assert.equal(reset.saturation, 1) -}) - -test('clipped atoms cannot be picked and changing planes updates existing hit targets', () => { - const mesh = new Mesh(new SphereGeometry(1), new MeshPhongMaterial()) - mesh.updateMatrixWorld(true) - const ray = new Raycaster(new Vector3(0.1, 0.1, 5), new Vector3(0, 0, -1)) - clip_rep_raycast(mesh, () => [new Plane(new Vector3(1, 0, 0), -2)]) - assert.equal(ray.intersectObject(mesh).length, 0) - clip_rep_raycast(mesh, () => []) - assert.ok(ray.intersectObject(mesh).length > 0) - mesh.geometry.dispose(); (mesh.material as MeshPhongMaterial).dispose() -}) - - -test('datasets sharing one file keep their independent slot identities after reordering', () => { - const entries = [{ path: 'both.cube' }, { path: 'both.cube' }, { path: 'other.cube' }] - const rep = create_rep(dataset_source(entries, 1), 'second-grid') - rep.volume.colorSourcePath = 'both.cube'; rep.volume.colorSourceSlot = 0 - const restored = remap_rep_sources({ items: [rep], selectedId: rep.id }, [{ path: 'other.cube' }, ...entries.slice(0, 2)]).items[0] - assert.equal(restored.source.kind === 'volume' && restored.source.index, 2) - assert.equal(restored.volume.color_volume_idx, 1) - assert.equal((remap_rep_sources({ items: [rep], selectedId: rep.id }, entries.slice(0, 1)).items[0].source as { index: number }).index, -1) -}) - -test('legacy supercells and whole boundary atom choices survive migration', () => { - const migrated = migrate_reps({}, rep_surface_settings(create_rep({ kind: 'structure' })), [], true, - { atomSupercell: '2x1x1', showBoundaryAtoms: false, showUnitCell: false }).items[0] - assert.deepEqual(migrated.periodic.range, [[0, 2], [0, 1], [0, 1]]) - assert.equal(migrated.periodic.showCell, false) - const boundarySource = { ...source, sites: [{ ...source.sites[0], xyz: [0, 0, 0] as [number, number, number] }] } - assert.equal(rep_structure(boundarySource, migrated, cubic).structure.sites.length, 2) - migrated.periodic.boundary = 'atoms' - assert.equal(rep_structure(boundarySource, migrated, cubic).structure.sites.length, 12) -}) - -test('numeric radii match the renderer, glass is transparent, malformed collections are rejected', () => { - const rep = create_rep({ kind: 'structure' }) - rep.structure.style = 'spacefill'; rep.structure.radius = 1.1 - assert.equal(rep_scene_props(rep).atom_radius, 1.1) - assert.equal(material_preset(rep.material, 'glass1').opacity, 0.35) - assert.throws(() => normalize_reps({}), /Invalid representations/) - assert.throws(() => normalize_reps(null), /Invalid representations/) - assert.equal(normalize_reps(undefined), undefined) -}) - - -test('fit-to-view excludes clipped guard geometry and handles empty and skew intersections', () => { - const bounds = new Box3(new Vector3(-5, -5, -5), new Vector3(5, 5, 5)) - const rep = create_rep({ kind: 'structure' }) - rep.periodic.enabled = true - rep.periodic.range = [[0, 0.5], [0, 0.5], [0, 0.5]] - const clipped = clipped_rep_bounds(bounds, rep_clip_planes(rep.periodic, [[4, 0, 0], [1, 4, 0], [0, 0, 4]])) - assert.deepEqual(clipped.min.toArray(), [0, 0, 0]) - assert.deepEqual(clipped.max.toArray(), [2.5, 2, 2]) - assert.equal(clipped_rep_bounds(bounds, [new Plane(new Vector3(1, 0, 0), -6)]).isEmpty(), true) -}) - - -test('removing an earlier dataset from the same file preserves the retained dataset identity', () => { - const entries = [{ path: 'both.cube', datasetSlot: 0 }, { path: 'both.cube', datasetSlot: 1 }] - const rep = create_rep(dataset_source(entries, 1), 'second-grid') - rep.volume.colorSourcePath = 'both.cube'; rep.volume.colorSourceSlot = 0 - const restored = remap_rep_sources({ items: [rep], selectedId: rep.id }, entries.slice(1)).items[0] - assert.equal(restored.source.kind === 'volume' && restored.source.index, 0) - assert.equal(restored.volume.color_volume_idx, -1, 'missing color source cannot silently use another grid') -}) - - -test('native bond edits map to each independently selected and repeated display', () => { - const rep = create_rep({ kind: 'structure' }) - rep.periodic.enabled = true; rep.periodic.boundary = 'none'; rep.periodic.range[0] = [0, 2] - const display = rep_structure(source, rep, cubic) - const edits = [{ site_idx_1: 0, site_idx_2: 1, order: 3 as const }] - const mapped = rep_bonds(display, edits, true) - assert.equal(mapped.length, 2) - for (const bond of mapped) { - assert.equal(display.sourceIndices[bond.site_idx_1], 0) - assert.equal(display.sourceIndices[bond.site_idx_2], 1) - assert.deepEqual(display.shifts[bond.site_idx_1], display.shifts[bond.site_idx_2]) - assert.equal(bond.order, 3) - } - rep.structure.selection = 'index 1' - assert.deepEqual(rep_bonds(rep_structure(source, rep, cubic), edits, true), []) -}) diff --git a/frontend/matterviz-viewer/tests/scalar-grid-transfer.test.ts b/frontend/matterviz-viewer/tests/scalar-grid-transfer.test.ts deleted file mode 100644 index 766a4f09..00000000 --- a/frontend/matterviz-viewer/tests/scalar-grid-transfer.test.ts +++ /dev/null @@ -1,215 +0,0 @@ -import assert from 'node:assert/strict' -import test from 'node:test' -import { createServer, type ViteDevServer } from 'vite' - -let server: ViteDevServer -let geometry: any - -test.before(async () => { - server = await createServer({ - configFile: false, - server: { middlewareMode: true, watch: null }, - appType: 'custom', - optimizeDeps: { noDiscovery: true }, - }) - const marching = await server.ssrLoadModule('/node_modules/matterviz/dist/marching-cubes.js') - class FakeWorker { - onmessage?: (event: MessageEvent) => void - onerror?: (event: ErrorEvent) => void - terminate(): void {} - postMessage(message: any, transfer: Transferable[] = []): void { - try { - const transferred = structuredClone(message, { transfer }) - const result = marching.marching_cubes_typed( - transferred.grid, - transferred.iso_value, - transferred.lattice, - transferred.options, - ) - const response = { - job_id: transferred.job_id, - ok: true, - positions: result.positions.buffer, - normals: result.normals.buffer, - indices: result.indices.buffer, - data_buffer: transferred.grid.data.buffer, - estimate: marching.preflight_marching_cubes( - transferred.grid, - transferred.iso_value, - transferred.options, - ), - } - queueMicrotask(() => this.onmessage?.({ data: response } as MessageEvent)) - } catch (error) { - queueMicrotask(() => this.onerror?.({ message: String(error) } as ErrorEvent)) - } - } - } - ;(globalThis as any).Worker = FakeWorker - geometry = await server.ssrLoadModule('/node_modules/matterviz/dist/isosurface/geometry.js') -}) - -test.after(async () => { - delete (globalThis as any).Worker - await server.close() -}) - -test('transferred ordinary ArrayBuffer is returned and restored after worker completion', async () => { - const backing = new ArrayBuffer(304 + 8 * Float64Array.BYTES_PER_ELEMENT) - const backingBytes = backing.byteLength - const data = new Float64Array(backing, 304, 8) - data.set([0, 1, 1, 0, 1, 0, 0, 1]) - const grid = { - data, - dimensions: [2, 2, 2] as [number, number, number], - order: 'x-fastest' as const, - } - const before = Array.from(grid.data) - await geometry.request_isosurface_geometry( - grid, - 0.5, - [[1, 0, 0], [0, 1, 0], [0, 0, 1]], - { periodic: false, centered: false, normals: true }, - ) - assert.deepEqual(Array.from(grid.data), before) - assert.equal(grid.data.byteOffset, 304) - assert.equal(grid.data.length, 8) - assert.equal(grid.data.buffer.byteLength, backingBytes) -}) - -test('a newer generation wins when requests overlap on one grid', async () => { - const grid = { - data: new Float32Array([0, 1, 1, 0, 1, 0, 0, 1]), - dimensions: [2, 2, 2] as [number, number, number], - order: 'x-fastest' as const, - } - const options = { periodic: false, centered: false, normals: true } - const first = geometry.request_isosurface_geometry(grid, 0.5, [[1, 0, 0], [0, 1, 0], [0, 0, 1]], options) - const second = geometry.request_isosurface_geometry(grid, 0.25, [[1, 0, 0], [0, 1, 0], [0, 0, 1]], options) - const [first_result, second_result] = await Promise.all([first, second]) - assert.equal(first_result.stale, true) - assert.equal(second_result.stale, undefined) -}) - -test('worker messages normalize proxied grid metadata arrays', async (t) => { - if (typeof SharedArrayBuffer === 'undefined') { - t.skip('SharedArrayBuffer is unavailable') - return - } - const shared = new SharedArrayBuffer(8 * Float32Array.BYTES_PER_ELEMENT) - const data = new Float32Array(shared) - data.set([0, 1, 1, 0, 1, 0, 0, 1]) - const proxied = (values: number[]) => new Proxy(values, {}) - const grid = { - data, - dimensions: proxied([2, 2, 2]), - order: 'x-fastest' as const, - } - const lattice = new Proxy([ - proxied([1, 0, 0]), - proxied([0, 1, 0]), - proxied([0, 0, 1]), - ], {}) - const result = await geometry.request_isosurface_geometry( - grid, - 0.5, - lattice, - new Proxy({ periodic: false, centered: false, normals: true }, {}), - ) - assert.ok(result.positions.length > 0) - assert.equal(grid.data.buffer, shared) -}) - -test('releasing a volume terminates its worker and drops queued geometry work', async (t) => { - if (typeof SharedArrayBuffer === 'undefined') { - t.skip('SharedArrayBuffer is unavailable') - return - } - let terminated = 0 - class PendingWorker { - onmessage?: (event: MessageEvent) => void - onerror?: (event: ErrorEvent) => void - postMessage(): void {} - terminate(): void { terminated += 1 } - } - const previousWorker = (globalThis as any).Worker - ;(globalThis as any).Worker = PendingWorker - try { - const shared = new SharedArrayBuffer(8 * Float32Array.BYTES_PER_ELEMENT) - const grid = { - data: new Float32Array(shared), - dimensions: [2, 2, 2] as [number, number, number], - order: 'x-fastest' as const, - } - const request = geometry.request_isosurface_geometry( - grid, - 0.5, - [[1, 0, 0], [0, 1, 0], [0, 0, 1]], - { periodic: false }, - ) - const queued = geometry.request_isosurface_geometry( - grid, - 0.25, - [[1, 0, 0], [0, 1, 0], [0, 0, 1]], - { periodic: false }, - ) - const rejections = Promise.all([ - assert.rejects(request, (error: any) => error?.code === 'geometry-released'), - assert.rejects(queued, (error: any) => error?.code === 'geometry-released'), - ]) - await new Promise((resolve) => setImmediate(resolve)) - geometry.release_isosurface_geometry(grid) - await rejections - assert.equal(terminated, 1) - assert.equal(grid.data.buffer, shared) - assert.equal(grid.data.length, 8) - } finally { - ;(globalThis as any).Worker = previousWorker - } -}) - -test('releasing transferred typed data invalidates the removed grid without copying it back', async () => { - let terminated = 0 - class PendingWorker { - onmessage?: (event: MessageEvent) => void - onerror?: (event: ErrorEvent) => void - postMessage(): void {} - terminate(): void { terminated += 1 } - } - const previousWorker = (globalThis as any).Worker - ;(globalThis as any).Worker = PendingWorker - try { - const original = new ArrayBuffer(8 * Float32Array.BYTES_PER_ELEMENT) - const grid = { - data: new Float32Array(original), - dimensions: [2, 2, 2] as [number, number, number], - order: 'x-fastest' as const, - } - const request = geometry.request_isosurface_geometry( - grid, - 0.5, - [[1, 0, 0], [0, 1, 0], [0, 0, 1]], - { periodic: false }, - ) - const rejection = assert.rejects(request, (error: any) => error?.code === 'geometry-released') - await new Promise((resolve) => setImmediate(resolve)) - geometry.release_isosurface_geometry(grid) - await rejection - assert.equal(terminated, 1) - assert.equal(grid.data.length, 0) - assert.notEqual(grid.data.buffer, original) - } finally { - ;(globalThis as any).Worker = previousWorker - } -}) - -test('disposing unretained geometry is immediate and leaves retained resources intact', () => { - const disposed: string[] = [] - const entries = ['old', 'current'].map((geo_key) => ({ - geo_key, - geometry: { dispose: () => disposed.push(geo_key) }, - })) - const retained = geometry.dispose_unretained_geometries(entries, new Set(['current'])) - assert.deepEqual(disposed, ['old']) - assert.deepEqual(retained, [entries[1]]) -}) diff --git a/frontend/matterviz-viewer/tests/scalar-grid-worker.test.ts b/frontend/matterviz-viewer/tests/scalar-grid-worker.test.ts deleted file mode 100644 index b9c8c403..00000000 --- a/frontend/matterviz-viewer/tests/scalar-grid-worker.test.ts +++ /dev/null @@ -1,112 +0,0 @@ -import assert from 'node:assert/strict' -import { readFile } from 'node:fs/promises' -import test from 'node:test' -import { createServer, type ViteDevServer } from 'vite' - -let server: ViteDevServer -let marching: any -let geometry: any - -test.before(async () => { - server = await createServer({ - configFile: false, - server: { middlewareMode: true, watch: null }, - appType: 'custom', - optimizeDeps: { noDiscovery: true }, - }) - marching = await server.ssrLoadModule('/node_modules/matterviz/dist/marching-cubes.js') - geometry = await server.ssrLoadModule('/node_modules/matterviz/dist/isosurface/geometry.js') -}) - -test.after(async () => { - await server.close() -}) - -const lattice = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] - -function grid(values: number[], dimensions: [number, number, number] = [2, 2, 2]) { - return { - data: new Float32Array(values), - dimensions, - order: 'x-fastest' as const, - } -} - -test('preflight exactly matches typed marching output on representative fields', () => { - const fields = [ - grid(new Array(8).fill(1)), - grid([0, 0, 0, 0, 1, 1, 1, 1]), - grid([0, 1, 1, 0, 1, 0, 0, 1]), - grid([0, 1, 0, 1, 1, 0, 1, 0]), - grid(Array.from({ length: 27 }, (_, index) => Math.sin(index * 1.7)), [3, 3, 3]), - ] - for (const field of fields) { - const estimate = marching.preflight_marching_cubes(field, 0.5, { periodic: false, normals: true }) - const result = marching.marching_cubes_typed(field, 0.5, lattice, { - periodic: false, - centered: false, - normals: true, - }) - assert.equal(estimate.vertex_count, result.positions.length / 3) - assert.equal(estimate.triangle_count, result.indices.length / 3) - assert.ok(estimate.total_bytes >= estimate.working_bytes + estimate.gpu_bytes) - assert.ok(estimate.total_bytes > estimate.positions_bytes + estimate.normals_bytes + estimate.indices_bytes) - } -}) - -test('flat x-fastest and z-fastest worker geometry has sync parity', async () => { - const x = grid([0, 1, 1, 0, 1, 0, 0, 1]) - const z = { - data: new Float32Array([0, 1, 1, 0, 1, 0, 0, 1]), - dimensions: [2, 2, 2] as [number, number, number], - order: 'z-fastest' as const, - } - const sync = marching.marching_cubes_typed(x, 0.5, lattice, { periodic: false, centered: false, normals: true }) - const worker_x = await geometry.request_isosurface_geometry(x, 0.5, lattice, { periodic: false, centered: false, normals: true }) - const worker_z = await geometry.request_isosurface_geometry(z, 0.5, lattice, { periodic: false, centered: false, normals: true }) - assert.deepEqual(Array.from(worker_x.positions), Array.from(sync.positions)) - assert.deepEqual(Array.from(worker_x.normals), Array.from(sync.normals)) - assert.deepEqual(Array.from(worker_x.indices), Array.from(sync.indices)) - assert.deepEqual(Array.from(worker_z.positions), Array.from(sync.positions)) - assert.deepEqual(Array.from(worker_z.indices), Array.from(sync.indices)) -}) - -test('memory budget rejects before geometry allocation', () => { - const field = grid([0, 1, 1, 0, 1, 0, 0, 1]) - assert.throws( - () => geometry.geometry_preflight(field, 0.5, { periodic: false, geometry_memory_budget_bytes: 1 }), - (error: any) => error.code === 'geometry-memory-budget' && error.estimate.total_bytes > 1, - ) -}) - -test('ordinary ArrayBuffer grid content survives coordinator completion', async () => { - const field = grid([0, 1, 1, 0, 1, 0, 0, 1]) - const before = Array.from(field.data) - await geometry.request_isosurface_geometry(field, 0.5, lattice, { periodic: false, centered: false, normals: true }) - assert.deepEqual(Array.from(field.data), before) -}) - -test('standard flat geometry preparation bypasses the legacy downsample budget', async () => { - const source = await readFile(new URL('../node_modules/matterviz/dist/isosurface/Isosurface.svelte', import.meta.url), 'utf8') - // The shared preparation helper now owns this fast path. Its executable - // upstream regression verifies buffer identity and physical voxel spacing. - assert.match(source, /preserve_source_grid/) - assert.match(source, /prepare_geometry_grid\(vol, effective_range\(vol\)/) - assert.match(source, /preserve_grid,/) -}) - -test('worker URL uses a Vite-static module expression', async () => { - const source = await readFile(new URL('../node_modules/matterviz/dist/isosurface/geometry.js', import.meta.url), 'utf8') - assert.match(source, /new Worker\(new URL\(`\.\/marching-cubes-worker\.js`, import\.meta\.url\), \{ type: `module` \}\)/) - assert.match(source, /new Ctor\(buffer, byte_offset, length\)/) -}) - -test('one geometry budget is shared by all resident surfaces', async () => { - const source = await readFile(new URL('../node_modules/matterviz/dist/isosurface/Isosurface.svelte', import.meta.url), 'utf8') - assert.match(source, /committed_budget_bytes = retained_entries\.reduce/) - assert.equal(geometry.remaining_geometry_budget(undefined, 100), undefined) - assert.equal(geometry.remaining_geometry_budget(1000, 250), 750) - assert.equal(geometry.remaining_geometry_budget(1000, 1200), 0) - assert.match(source, /remaining_geometry_budget\(\s*total_budget,\s*committed_budget_bytes/) - assert.match(source, /committed_budget_bytes \+= geometry_budget_bytes/) -}) diff --git a/frontend/matterviz-viewer/tests/scalar-grid.test.ts b/frontend/matterviz-viewer/tests/scalar-grid.test.ts deleted file mode 100644 index cf6dbc07..00000000 --- a/frontend/matterviz-viewer/tests/scalar-grid.test.ts +++ /dev/null @@ -1,119 +0,0 @@ -import assert from 'node:assert/strict' -import test from 'node:test' -import { createServer, type ViteDevServer } from 'vite' - -type Grid = number[][][] | { - data: Float32Array | Float64Array - dimensions: [number, number, number] - order: 'x-fastest' | 'z-fastest' -} - -let server: ViteDevServer -let types: any -let sampling: any -let marching: any -let slice: any - -test.before(async () => { - server = await createServer({ - configFile: false, - server: { middlewareMode: true, watch: null }, - appType: 'custom', - optimizeDeps: { noDiscovery: true }, - }) - types = await server.ssrLoadModule('/node_modules/matterviz/dist/isosurface/types.js') - sampling = await server.ssrLoadModule('/node_modules/matterviz/dist/isosurface/sampling.js') - marching = await server.ssrLoadModule('/node_modules/matterviz/dist/marching-cubes.js') - slice = await server.ssrLoadModule('/node_modules/matterviz/dist/isosurface/slice.js') -}) - -test.after(async () => { - await server.close() -}) - -const dims: [number, number, number] = [3, 3, 3] -const value = (x: number, y: number, z: number): number => x + 10 * y + 100 * z -const nested: number[][][] = Array.from({ length: dims[0] }, (_, x) => - Array.from({ length: dims[1] }, (_, y) => - Array.from({ length: dims[2] }, (_, z) => value(x, y, z)), - ), -) -const flat_grid = (order: 'x-fastest' | 'z-fastest'): Grid => { - const data = new Float64Array(dims[0] * dims[1] * dims[2]) - for (let x = 0; x < dims[0]; x += 1) { - for (let y = 0; y < dims[1]; y += 1) { - for (let z = 0; z < dims[2]; z += 1) { - const index = order === 'x-fastest' - ? x + dims[0] * (y + dims[1] * z) - : z + dims[2] * (y + dims[1] * x) - data[index] = value(x, y, z) - } - } - } - return { data, dimensions: dims, order } -} - -const volume = (grid: Grid) => ({ - grid, - grid_dims: dims, - lattice: [[3, 0, 0], [0, 3, 0], [0, 0, 3]], - origin: [0, 0, 0], - data_range: types.grid_data_range(grid), - periodic: true, -}) - -test('flat x-fastest, flat z-fastest, and legacy grids are behaviorally equal', () => { - const grids = [nested, flat_grid('x-fastest'), flat_grid('z-fastest')] - const range = grids.map((grid) => types.grid_data_range(grid)) - assert.deepEqual(range[1], range[0]) - assert.deepEqual(range[2], range[0]) - - const samples = grids.map((grid) => sampling.trilinear_interpolate(grid, 0.25, 0.5, 0.75, true)) - assert.deepEqual(samples, [samples[0], samples[0], samples[0]]) - - const meshes = grids.map((grid) => marching.marching_cubes( - grid, - 111, - [[1, 0, 0], [0, 1, 0], [0, 0, 1]], - { periodic: false, centered: false, normals: false }, - )) - assert.deepEqual(meshes[1], meshes[0]) - assert.deepEqual(meshes[2], meshes[0]) -}) - -test('downsample, periodic padding, tiling, range extraction, and slices share the accessor', () => { - const grids = [nested, flat_grid('x-fastest'), flat_grid('z-fastest')] - const downsampled = grids.map((grid) => types.downsample_grid(grid, dims, 8).grid) - const padded = grids.map((grid) => types.pad_periodic_grid(grid, dims, 0.34).grid) - const tiled = grids.map((grid) => types.tile_volumetric_data(volume(grid), [2, 1, 1]).grid) - const extracted = grids.map((grid) => sampling.extract_volume_range(volume(grid), [[0, 1], [0, 1], [0, 1]]).grid) - const read = (grid: Grid, shape: [number, number, number]) => Array.from( - { length: shape[0] * shape[1] * shape[2] }, - (_, index) => { - const x = index % shape[0] - const y = Math.floor(index / shape[0]) % shape[1] - const z = Math.floor(index / (shape[0] * shape[1])) - return types.grid_value(grid, x, y, z, shape) - }, - ) - assert.deepEqual(read(downsampled[1], [2, 2, 2]), read(downsampled[0], [2, 2, 2])) - assert.deepEqual(read(downsampled[2], [2, 2, 2]), read(downsampled[0], [2, 2, 2])) - assert.deepEqual(read(padded[1], [5, 5, 5]), read(padded[0], [5, 5, 5])) - assert.deepEqual(read(tiled[1], [6, 3, 3]), read(tiled[0], [6, 3, 3])) - assert.deepEqual(read(extracted[1], [4, 4, 4]), read(extracted[0], [4, 4, 4])) - - const slices = grids.map((grid) => slice.sample_hkl_slice(volume(grid), [0, 0, 1], 0.5, 4)) - assert(slices[0] && slices[1] && slices[2]) - assert.deepEqual(Array.from(slices[1].data), Array.from(slices[0].data)) - assert.deepEqual(Array.from(slices[2].data), Array.from(slices[0].data)) -}) - -test('large typed grids remain one typed buffer through preparation', () => { - const data = new Float32Array(10_000_000) - const grid: Grid = { data, dimensions: [100, 100, 1000], order: 'z-fastest' } - const result = types.downsample_grid(grid, [100, 100, 1000], 500_000) - assert(data instanceof Float32Array) - assert(result.grid.data instanceof Float32Array) - assert.equal(Array.isArray(result.grid), false) - assert.equal(result.grid.data.length, result.grid.dimensions[0] * result.grid.dimensions[1] * result.grid.dimensions[2]) -}) diff --git a/frontend/matterviz-viewer/tests/slice.test.ts b/frontend/matterviz-viewer/tests/slice.test.ts deleted file mode 100644 index d298d1cf..00000000 --- a/frontend/matterviz-viewer/tests/slice.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -import assert from 'node:assert/strict' -import test from 'node:test' -import { AXIS_PRESETS, axis_to_miller, normalize_miller_indices, normalize_slice_resolution, normalize_slice_result, resolve_slice_range, sample_slice_with, scalar_to_rgba, slice_to_rgba } from '../src/slice.ts' - -const volume = { - grid: Array.from({ length: 4 }, (_, x) => Array.from({ length: 4 }, (_, y) => Array.from({ length: 4 }, (_, z) => x + y * 10 + z * 100))), - grid_dims: [4, 4, 4] as [number, number, number], - lattice: [[1, 0, 0], [0, 1, 0], [0, 0, 1]] as [[number, number, number], [number, number, number], [number, number, number]], - origin: [0, 0, 0] as [number, number, number], - data_range: { min: 0, max: 333, abs_max: 333, mean: 166.5 }, - periodic: true, -} - -test('maps standard plane presets to Miller indices', () => { - assert.deepEqual(axis_to_miller('xy'), [0, 0, 1]) - assert.deepEqual(axis_to_miller('xz'), [0, 1, 0]) - assert.deepEqual(axis_to_miller('yz'), [1, 0, 0]) - assert.deepEqual(AXIS_PRESETS.xy, [0, 0, 1]) - assert.deepEqual(normalize_miller_indices(['bad', 1.8, Infinity]), [0, 2, 0]) -}) - -test('normalizes malformed sample results and ignores non-finite data', () => { - const result = normalize_slice_result({ width: 2, height: 2, data: [1, Number.NaN, 4] }) - assert(result) - assert.deepEqual([...result.data], [1, Number.NaN, 4, Number.NaN]) - assert.equal(result.min, 1) - assert.equal(result.max, 4) - assert.equal(normalize_slice_result({ width: 0, height: 2, data: [1] }), null) -}) - -test('samples a normalized MatterViz HKL slice with clamped position', () => { - const sampler = (_volume: typeof volume, miller: [number, number, number], distance: number, points = 4) => ({ - data: new Float64Array(points * points).fill(distance + miller[2]), - width: points, - height: points, - min: distance + miller[2], - max: distance + miller[2], - }) - const result = sample_slice_with(sampler, volume, [0, 0, 1], 10, 6) - assert(result) - assert.equal(result.width, 6) - assert.equal(result.height, 6) - assert(Number.isFinite(result.min)) - assert(Number.isFinite(result.max)) - assert.equal(sample_slice_with(sampler, volume, [0, 0, 0], 0.5, 6), null) -}) - -test('clamps slice resolution to a safe quadratic workload', () => { - assert.equal(normalize_slice_resolution(1), 2) - assert.equal(normalize_slice_resolution(128.9), 128) - assert.equal(normalize_slice_resolution(5000), 512) - assert.equal(normalize_slice_resolution('bad'), 128) -}) - -test('resolves auto/manual ranges, reversed bounds, constants, and invalid values', () => { - assert.deepEqual(resolve_slice_range([1, Number.NaN, 5]), [1, 5]) - assert.deepEqual(resolve_slice_range([1, 2], 8, 3), [3, 8]) - assert.deepEqual(resolve_slice_range([1, 2], '', ''), [1, 2]) - assert.deepEqual(resolve_slice_range([1, 2], null, undefined), [1, 2]) - assert.deepEqual(resolve_slice_range([null, 4] as unknown as number[]), [4, 4]) - assert.deepEqual(resolve_slice_range([Number.NaN]), [0, 1]) - assert.deepEqual(resolve_slice_range([4, 4]), [4, 4]) -}) - -test('maps values to clamped RGBA bytes for continuous colormaps', () => { - assert.deepEqual(scalar_to_rgba(0, [0, 1], 'Viridis').slice(3), [255]) - assert.deepEqual(scalar_to_rgba(Number.NaN, [0, 1]), [0, 0, 0, 0]) - const rgba = slice_to_rgba({ data: new Float64Array([0, 0.5, 1, Number.NaN]), width: 2, height: 2, min: 0, max: 1 }, [0, 1], 'Viridis') - assert.equal(rgba.length, 16) - assert.equal(rgba[15], 0) - assert.notDeepEqual([...rgba.slice(0, 4)], [...rgba.slice(4, 8)]) -}) diff --git a/frontend/matterviz-viewer/tests/state.test.ts b/frontend/matterviz-viewer/tests/state.test.ts deleted file mode 100644 index 77076206..00000000 --- a/frontend/matterviz-viewer/tests/state.test.ts +++ /dev/null @@ -1,376 +0,0 @@ -import assert from 'node:assert/strict' -import test from 'node:test' -import { - create_workbench_state, - parse_workbench_state, - restore_workbench_state, -} from '../src/state.ts' - -test('serializes volume, cross-coloring, and periodic display state', () => { - const state = create_workbench_state({ - manifest: { periodic: { enabled: true } }, - sourceManifest: 'http://127.0.0.1/session/manifest.json', - entries: [{ path: 'density.cube', role: 'density' }, { path: 'esp.cube', role: 'esp' }], - isosurfaceSettings: { - display_range: [[-1, 2], [0, 1], [0.5, 3]], - layers: [{ - volume_idx: 0, - color_volume_idx: 1, - isovalue: 0.001, - opacity: 0.8, - visible: true, - color: '#123456', - negative_color: '#654321', - show_negative: true, - colormap: 'interpolateRdBu', - color_range: [-0.05, 0.05], - }], - }, - activeVolume: 0, - atomSupercell: '2x1x1', - showBoundaryAtoms: true, - showUnitCell: false, - }) - assert.equal(state.format, 'multiwfn-matterviz-workbench') - assert.equal(state.volumes[0].colorVolumeIndex, 1) - assert.deepEqual(state.volumes[0].colorRange, [-0.05, 0.05]) - assert.equal(state.volumes[0].color, '#123456') - assert.equal(state.volumes[0].negativeColor, '#654321') - assert.equal(state.volumes[0].showNegative, true) - assert.deepEqual(state.periodic?.displayRange, [[-1, 2], [0, 1], [0.5, 3]]) -}) - -test('omits invalid display ranges and clamps the active index', () => { - const state = create_workbench_state({ - manifest: { periodic: { enabled: true } }, - entries: [], - isosurfaceSettings: { display_range: [[0, 1], [0, Number.NaN], [0, 1]] }, - activeVolume: 30, - atomSupercell: '1x1x1', - showBoundaryAtoms: false, - showUnitCell: true, - }) - assert.equal(state.activeVolume, 0) - assert.equal(state.periodic?.displayRange, undefined) -}) - -test('round-trips camera state and restores appearance by volume index', () => { - const exported = create_workbench_state({ - manifest: { periodic: { enabled: true } }, - entries: [{ path: 'density.cube' }, { path: 'esp.cube' }], - isosurfaceSettings: { - isovalue: 0.1, - opacity: 0.9, - positive_color: '#000', - negative_color: '#fff', - show_negative: true, - wireframe: true, - material: 'pbr', - roughness: 0.2, - metalness: 0.3, - shininess: 0.4, - specular: 0.5, - halo: 0.6, - layers: [{ - volume_idx: 0, - isovalue: 0.01, - opacity: 0.75, - visible: true, - color: '#123456', - negative_color: '#654321', - show_negative: true, - color_volume_idx: 1, - }], - }, - activeVolume: 1, - atomSupercell: '2x1x1', - showBoundaryAtoms: true, - showUnitCell: false, - camera: { position: [1, 2, 3], target: [0, 0, 0], up: [0, 0, 1], zoom: 2.5, projection: 'orthographic' }, - }) - const parsed = parse_workbench_state(JSON.parse(JSON.stringify(exported))) - assert.deepEqual(parsed.camera, exported.camera) - assert.deepEqual(parsed.periodic, exported.periodic) - const restored = restore_workbench_state(parsed, { - entries: [{ path: 'density.cube' }], - isosurfaceSettings: { - isovalue: 1, - opacity: 1, - positive_color: '#aaa', - negative_color: '#bbb', - show_negative: false, - wireframe: false, - halo: 0, - layers: [{ volume_idx: 0, isovalue: 2, opacity: 0.2, visible: false, color: '#000', negative_color: '#111', show_negative: false }], - }, - }) - assert.equal(restored.activeVolume, 0) - assert.equal(restored.isosurfaceSettings.layers?.[0].color, '#123456') - assert.equal(restored.isosurfaceSettings.layers?.[0].negative_color, '#654321') - assert.equal(restored.isosurfaceSettings.layers?.[0].color_volume_idx, undefined) - assert.equal(restored.isosurfaceSettings.material, 'pbr') -}) - -test('rejects unsupported state versions and ignores malformed optional fields', () => { - assert.throws(() => parse_workbench_state({ format: 'other', version: 1, volumes: [] })) - assert.throws(() => parse_workbench_state({ format: 'multiwfn-matterviz-workbench', version: 2, volumes: [] })) - const parsed = parse_workbench_state({ - format: 'multiwfn-matterviz-workbench', - version: 1, - activeVolume: Number.NaN, - volumes: [{ path: 'density.cube', volumeIndex: 0, color: 7, colorRange: ['nope', 1], colormap: 'not-a-map' }], - camera: { position: [1, Number.NaN, 3], projection: 'invalid' }, - periodic: { atomSupercell: '1x1x1', showBoundaryAtoms: true, showUnitCell: false, displayRange: [[0, 1], [0, 1], [0, Number.NaN]] }, - }) - assert.equal(parsed.activeVolume, 0) - assert.equal(parsed.volumes[0].color, undefined) - assert.equal(parsed.volumes[0].colormap, undefined) - assert.equal(parsed.camera, undefined) - assert.equal(parsed.periodic?.displayRange, undefined) -}) - -test('clamps surface appearance on import, export and direct restore without filling omitted fields', () => { - const malformed = { - material: 'unlit', flatShading: true, - roughness: '-1', metalness: 4, shininess: 400, specular: -1, halo: 2, - outline: 2, outlineWidth: -1, transmode: 1, - } - const snapshot = { - format: 'multiwfn-matterviz-workbench', version: 1, activeVolume: 0, - volumes: [{ path: 'density.cube', volumeIndex: 0 }], session: {}, isosurface: malformed, - } - const expected = { - material: 'unlit', flatShading: true, - roughness: 0, metalness: 1, shininess: 120, specular: 0, halo: 1, - outline: 1, outlineWidth: 0, transmode: 1, - } - assert.deepEqual(parse_workbench_state(snapshot).isosurface, expected) - const exported = create_workbench_state({ - manifest: {}, entries: [{ path: 'density.cube' }], - isosurfaceSettings: { ...malformed, flat_shading: true }, activeVolume: 0, - atomSupercell: '1x1x1', showBoundaryAtoms: false, showUnitCell: false, - }) - assert.deepEqual(exported.isosurface, expected) - const restored = restore_workbench_state(snapshot, { entries: [{ path: 'density.cube' }], isosurfaceSettings: {} }) - assert.deepEqual(restored.isosurfaceSettings, { - layers: [], material: 'unlit', flat_shading: true, - roughness: 0, metalness: 1, shininess: 120, specular: 0, halo: 1, - outline: 1, outlineWidth: 0, transmode: 1, - }) - assert.equal(parse_workbench_state({ ...snapshot, isosurface: { - material: 'invalid', flatShading: 'yes', roughness: Number.NaN, halo: Number.POSITIVE_INFINITY, - outline: Number.NaN, outlineWidth: Number.NEGATIVE_INFINITY, transmode: 7, - } }).isosurface, undefined) - assert.equal(parse_workbench_state({ ...snapshot, isosurface: {} }).isosurface, undefined) -}) - -test('ignores malformed camera up and zoom while preserving valid camera fields', () => { - const parsed = parse_workbench_state({ - format: 'multiwfn-matterviz-workbench', - version: 1, - activeVolume: 0, - volumes: [], - camera: { - position: [1, 2, 3], - target: [0, 0, 0], - up: [0, Number.NaN, 1], - zoom: -2, - projection: 'orthographic', - }, - session: {}, - }) - assert.deepEqual(parsed.camera, { - position: [1, 2, 3], - target: [0, 0, 0], - up: undefined, - zoom: undefined, - projection: 'orthographic', - }) -}) - -test('preserves every colormap exposed by the layer controls', () => { - for (const colormap of ['interpolateRdBu', 'interpolateViridis', 'interpolateTurbo', 'interpolateCool', 'interpolateWarm', 'interpolateRdYlGn', 'interpolateGreys', 'interpolateTransFlag']) { - const parsed = parse_workbench_state({ - format: 'multiwfn-matterviz-workbench', - version: 1, - activeVolume: 0, - volumes: [{ path: 'density.cube', volumeIndex: 0, colormap }], - session: {}, - }) - assert.equal(parsed.volumes[0].colormap, colormap) - } -}) - -test('normalizes reversed persisted color ranges', () => { - const parsed = parse_workbench_state({ - format: 'multiwfn-matterviz-workbench', - version: 1, - activeVolume: 0, - volumes: [{ path: 'density.cube', volumeIndex: 0, colorRange: [0.2, -0.1] }], - session: {}, - }) - assert.deepEqual(parsed.volumes[0].colorRange, [-0.1, 0.2]) -}) - -test('round-trips structure appearance and background state', () => { - const exported = create_workbench_state({ - manifest: {}, - entries: [{ path: 'structure.cif' }], - isosurfaceSettings: {}, - activeVolume: 0, - atomSupercell: '1x1x1', - showBoundaryAtoms: true, - showUnitCell: true, - sceneProps: { - representation_preset: 'wire', - representation_atom_base: 0.8, - representation_bond_base: 0.04, - show_atoms: false, - show_bonds: 'molecules', - show_gizmo: false, - atom_radius: 1.25, - same_size_atoms: true, - bond_thickness: 0.2, - bonding_strategy: 'solid_angle', - show_site_labels: true, - show_site_indices: true, - sphere_segments: 32, - }, - backgroundColor: '#112233', - backgroundOpacity: 0.65, - }) - const expected = { - representationPreset: 'wire', - representationAtomBase: 0.8, - representationBondBase: 0.04, - showAtoms: false, - showBonds: 'molecules', - showGizmo: false, - atomRadius: 1.25, - sameSizeAtoms: true, - bondThickness: 0.2, - bondingStrategy: 'solid_angle', - showSiteLabels: true, - showSiteIndices: true, - sphereSegments: 32, - backgroundColor: '#112233', - backgroundOpacity: 0.65, - } - assert.deepEqual(exported.structureAppearance, expected) - const parsed = parse_workbench_state(JSON.parse(JSON.stringify(exported))) - assert.deepEqual(parsed.structureAppearance, expected) - const restored = restore_workbench_state(parsed, { entries: [{ path: 'structure.cif' }], isosurfaceSettings: {} }) - assert.deepEqual(restored.structureAppearance, expected) -}) - -test('round-trips true and false axes visibility and omits malformed legacy values', () => { - for (const showGizmo of [true, false]) { - const parsed = parse_workbench_state({ - format: 'multiwfn-matterviz-workbench', - version: 1, - activeVolume: 0, - volumes: [{ path: 'structure.cif', volumeIndex: 0 }], - structureAppearance: { showGizmo }, - session: {}, - }) - assert.equal(parsed.structureAppearance?.showGizmo, showGizmo) - } - const malformed = parse_workbench_state({ - format: 'multiwfn-matterviz-workbench', - version: 1, - activeVolume: 0, - volumes: [{ path: 'structure.cif', volumeIndex: 0 }], - structureAppearance: { showGizmo: 'yes' }, - session: {}, - }) - assert.equal(malformed.structureAppearance, undefined) -}) - -test('clamps bounded structure appearance values and ignores malformed fields', () => { - const parsed = parse_workbench_state({ - format: 'multiwfn-matterviz-workbench', - version: 1, - activeVolume: 0, - volumes: [{ path: 'structure.cif', volumeIndex: 0 }], - structureAppearance: { - representationPreset: 'invalid', - representationAtomBase: 'bad', - representationBondBase: Number.POSITIVE_INFINITY, - showAtoms: 'yes', - showBonds: 'invalid', - showGizmo: 'yes', - show_gizmo: 'no', - atomRadius: -10, - same_size_atoms: true, - bond_thickness: 10, - bondingStrategy: 'invalid', - show_site_labels: false, - showSiteIndices: Number.NaN, - sphere_segments: 100, - backgroundColor: ' ', - background_opacity: -1, - }, - session: {}, - }) - assert.deepEqual(parsed.structureAppearance, { - atomRadius: 0.1, - sameSizeAtoms: true, - bondThickness: 1, - showSiteLabels: false, - sphereSegments: 64, - backgroundOpacity: 0, - }) -}) - -test('round-trips slice controls and ESP legend placement', () => { - const exported = create_workbench_state({ - manifest: {}, - entries: [{ path: 'density.cube' }], - isosurfaceSettings: {}, - activeVolume: 0, - atomSupercell: '1x1x1', - showBoundaryAtoms: true, - showUnitCell: true, - slice: { - open: true, - plane: 'yz', - millerIndices: [1, -2, 3], - position: 0.75, - resolution: 256, - colormap: 'RdBu', - rangeMode: 'manual', - manualMin: -2, - manualMax: 4, - }, - espLegend: { visible: false, position: { left: 42, top: 18 } }, - }) - const parsed = parse_workbench_state(JSON.parse(JSON.stringify(exported))) - assert.deepEqual(parsed.slice, exported.slice) - assert.deepEqual(parsed.espLegend, exported.espLegend) - const restored = restore_workbench_state(parsed, { entries: [{ path: 'density.cube' }], isosurfaceSettings: {} }) - assert.deepEqual(restored.slice, exported.slice) - assert.deepEqual(restored.espLegend, exported.espLegend) -}) - -test('normalizes malformed optional slice and legend fields', () => { - const parsed = parse_workbench_state({ - format: 'multiwfn-matterviz-workbench', - version: 1, - activeVolume: 0, - volumes: [{ path: 'density.cube', volumeIndex: 0 }], - slice: { - plane: 'bad', - millerIndices: [1, Number.NaN, 3], - position: 4, - resolution: 999, - colormap: 'bad', - rangeMode: 'invalid', - manualMin: 'nope', - manualMax: 2, - }, - espLegend: { visible: 'yes', position: { left: Number.NaN, top: 2 } }, - session: {}, - }) - assert.deepEqual(parsed.slice, { position: 1, resolution: 512, manualMax: 2 }) - assert.equal(parsed.espLegend, undefined) -}) diff --git a/frontend/matterviz-viewer/tests/surface-analysis.test.ts b/frontend/matterviz-viewer/tests/surface-analysis.test.ts index f26ed3c9..a6a9b17d 100644 --- a/frontend/matterviz-viewer/tests/surface-analysis.test.ts +++ b/frontend/matterviz-viewer/tests/surface-analysis.test.ts @@ -94,17 +94,6 @@ test('render winding is consistent, outward, and leaves native facets unchanged' assert.deepEqual(Array.from(r.indices), original) }) -test('surface view masks only volume meshes, retaining bonds, controls and the shared scene', async () => { - const root = new URL('../node_modules/matterviz/dist/structure/', import.meta.url) - for (const file of ['Structure.svelte', 'StructureViewport.svelte', 'StructureScene.svelte']) { - const text = await readFile(new URL(file, root), 'utf8') - assert.match(text, /surface_view\?: boolean/) - } - const scene = await readFile(new URL('StructureScene.svelte', root), 'utf8') - assert.match(scene, /Isosurface rendering[\s\S]*?/) - assert.match(scene, //) - assert.doesNotMatch(scene, /\{#if !surface_view/) -}) test('unknown metadata retains geometry without inventing mapping, volume or mass density', async () => { const m: SurfaceMetadata = { ...metadata(), surfaceType: null, mappedFunction: null, mapped: null, volume: null, massDensity: null, extrema: 0, metadataSource: 'unconfirmed' } diff --git a/frontend/matterviz-viewer/tests/topology.test.ts b/frontend/matterviz-viewer/tests/topology.test.ts index d3fa0364..bd7a3f98 100644 --- a/frontend/matterviz-viewer/tests/topology.test.ts +++ b/frontend/matterviz-viewer/tests/topology.test.ts @@ -2,7 +2,6 @@ import assert from 'node:assert/strict' import test from 'node:test' import { readFile } from 'node:fs/promises' import { AIM_DEFAULTS, BOHR_TO_ANGSTROM, normalize_topology_display, parse_topology, resolve_topology, topology_csv, topology_document, topology_path_length, topology_path_points, topology_scene_data, type Topology } from '../src/topology.ts' -import { create_workbench_state, parse_workbench_state, restore_workbench_state } from '../src/state.ts' const metadata = (): Topology => ({ version: 1, coordinateUnit: 'bohr', functionId: 1, datasetId: 9, hasDensity: true, eulerCount: 1, missingPathDirections: 1, criticalPoints: [{ id: 1, type: 2, density: .1, laplacian: -.3 }, { id: 2, type: 1, density: .8, laplacian: -2 }], @@ -63,30 +62,7 @@ test('exports retain raw Bohr coordinates, scalar properties and every path poin assert.match(csv.at(-1)!, /path,1,1,2,0.2,0,0,,,1,2/) }) -test('display settings round-trip independently of topology scientific data', () => { - const display = normalize_topology_display({ labels: true, radius: .13, width: 4, cpTypes: [false,true,true,false,true], pathTypes: [true,false,true,false] }) - const state = create_workbench_state({ manifest: {}, entries: [], isosurfaceSettings: {}, activeVolume: 0, atomSupercell: '1x1x1', showBoundaryAtoms: true, showUnitCell: false, topologyDisplay: display }) - const parsed = parse_workbench_state(JSON.parse(JSON.stringify(state))) - assert.deepEqual(parsed.topologyDisplay, display) - const restored = restore_workbench_state(parsed, { entries: [], isosurfaceSettings: {} }) - assert.deepEqual(restored.topologyDisplay, display) - assert.equal('criticalPoints' in state, false) - assert.deepEqual(normalize_topology_display({ radius: NaN, width: 100, cpTypes: [1] }), { cpTypes: [true,true,true,true,true], pathTypes: [true,true,true,true], radius: .09, width: 6, labels: false }) -}) -test('vendor exposes a shared scene slot and hides surfaces without unmounting', async () => { - const base = new URL('../node_modules/matterviz/dist/structure/', import.meta.url) - const scene = await readFile(new URL('StructureScene.svelte', base), 'utf8') - const structure = await readFile(new URL('Structure.svelte', base), 'utf8') - const declarations = await readFile(new URL('Structure.svelte.d.ts', base), 'utf8') - assert.match(scene, /\{@render scene_children\?\.\(\)\}/) - assert.match(scene, //) - assert.match(scene, /show_atoms \|\| topology_view/) - assert.doesNotMatch(scene, /\{#if !topology_view\}/) - assert.match(structure, /scene_props,\s+scene_children,\s+topology_view,/) - assert.match(declarations, /scene_children\?: Snippet/) - assert.match(declarations, /topology_view\?: boolean/) -}) test('the overlay does not alter atom identities or scalar geometry', async () => { const overlay = await readFile(new URL('../src/TopologyOverlay.svelte', import.meta.url), 'utf8') diff --git a/frontend/matterviz-viewer/tests/vendor-material.test.ts b/frontend/matterviz-viewer/tests/vendor-material.test.ts deleted file mode 100644 index d97d73cb..00000000 --- a/frontend/matterviz-viewer/tests/vendor-material.test.ts +++ /dev/null @@ -1,169 +0,0 @@ -import assert from 'node:assert/strict' -import { realpathSync } from 'node:fs' -import { readFile } from 'node:fs/promises' -import { createRequire } from 'node:module' -import test from 'node:test' -import { runInNewContext } from 'node:vm' -import { createServer } from 'vite' - -const installed = (path: string): URL => new URL(`../node_modules/matterviz/dist/${path}`, import.meta.url) -const three = createRequire(realpathSync(installed('isosurface/material.js')))('three') - -test('material shading modifies actual Three shader templates before include expansion', async () => { - const { install_isosurface_shading } = await import(installed('isosurface/material.js').href) - for (const [name, Material] of [ - ['lambert', three.MeshLambertMaterial], - ['phong', three.MeshPhongMaterial], - ['standard', three.MeshStandardMaterial], - ] as const) { - const material = new Material() - const original = three.ShaderLib[name].fragmentShader - assert.ok(!original.includes('gl_FragColor = vec4( outgoingLight, diffuseColor.a );')) - const shader = { fragmentShader: original, uniforms: {} as Record } - install_isosurface_shading(material, { outline: 0.6, outlineWidth: 0.8, transmode: 1 }) - material.onBeforeCompile(shader, null) - assert.notEqual(shader.fragmentShader, original, `${name} must actually receive the effect`) - for (const [uniform, value] of [['mvOutline', 0.6], ['mvOutlineWidth', 0.8], ['mvTransmode', 1]] as const) { - assert.equal(shader.uniforms[uniform].value, value) - assert.ok(shader.fragmentShader.includes(`uniform float ${uniform};`)) - } - const output = shader.fragmentShader.indexOf('#include ') - const shading = shader.fragmentShader.indexOf('gl_FragColor.rgb *=') - const toneMapping = shader.fragmentShader.indexOf('#include ') - assert.ok(output < shading && shading < toneMapping) - assert.match(shader.fragmentShader, /dot\(normal, geometryViewDir\)/) - assert.match(shader.fragmentShader, /gl_FragColor\.a > 0\.0 && gl_FragColor\.a < 1\.0/) - material.dispose() - } -}) - -test('material uniforms are bounded and a changed Three shader fails explicitly', async () => { - const { install_isosurface_shading } = await import(installed('isosurface/material.js').href) - const material = new three.MeshPhongMaterial() - install_isosurface_shading(material, { outline: 10, outlineWidth: Number.NaN, transmode: -1 }) - const shader = { fragmentShader: three.ShaderLib.phong.fragmentShader, uniforms: {} as Record } - material.onBeforeCompile(shader, null) - assert.deepEqual(Object.fromEntries(Object.entries(shader.uniforms).map(([key, uniform]) => [key, uniform.value])), { - mvOutline: 1, mvOutlineWidth: 0.6, mvTransmode: 0, - }) - assert.throws(() => material.onBeforeCompile({ fragmentShader: 'void main() {}', uniforms: {} }, null), /missing isosurface output chunk/) - material.dispose() -}) - -test('ESP vertex colors and colorbar share physical zero for asymmetric and one-sided ranges', async () => { - const vite = await createServer({ - configFile: false, - server: { middlewareMode: true, watch: null, hmr: false }, - appType: 'custom', - optimizeDeps: { noDiscovery: true }, - }) - try { - const { get_d3_interpolator, trans_flag_color } = await vite.ssrLoadModule('/node_modules/matterviz/dist/colors/index.js') - const { scalars_to_vertex_colors } = await vite.ssrLoadModule('/node_modules/matterviz/dist/isosurface/coloring.js') - const palette = get_d3_interpolator('interpolateTransFlag') - assert.deepEqual([palette(0), palette(0.5), palette(1)], ['#f5a9b8', '#ffffff', '#5bcefa']) - for (const range of [[-5, 20], [20, -5], [0, 20], [-5, 0], [2, 20], [-5, -2]]) { - const samples = new Float64Array([-5, 0, 20]) - const output = new Float32Array(samples.length * 3) - const colors = scalars_to_vertex_colors(samples, { colormap: 'interpolateTransFlag', color_range: range }, output) - assert.equal(colors, output, 'recoloring must reuse the provided allocation') - assert.deepEqual(Array.from(colors.slice(3, 6)), [1, 1, 1], `zero in ${range} must stay white`) - for (const [index, value] of samples.entries()) { - const expected = new three.Color(trans_flag_color(value, range)) - for (const [channel, component] of [expected.r, expected.g, expected.b].entries()) { - assert.ok(Math.abs(colors[index * 3 + channel] - component) < 1e-6) - } - } - } - assert.equal(trans_flag_color(-5, [-5, 20]), '#f5a9b8') - assert.equal(trans_flag_color(20, [-5, 20]), '#5bcefa') - const { trans_flag_color_css, esp_legend_gradient } = await vite.ssrLoadModule('/src/esp.ts') - for (const range of [[-5, 20], [2, 20], [-5, -2], [1, 1], [-1, -1], [0, 0]]) { - for (const value of [-5, 0, 1, 20]) { - assert.equal(trans_flag_color(value, range), trans_flag_color_css(value, ...range)) - } - if (range[0] === range[1]) { - assert.equal(esp_legend_gradient(...range), '#ffffff') - assert.deepEqual(Array.from(scalars_to_vertex_colors(new Float64Array([range[0]]), { - colormap: 'interpolateTransFlag', color_range: range, - })), [1, 1, 1]) - } - } - const colorbar = await readFile(installed('plot/core/components/ColorBar.svelte'), 'utf8') - assert.ok(colorbar.includes('trans_flag_color(value, range)')) - } finally { - await vite.close() - } -}) - -test('meshing Worker returns ordinary buffers on success and failure without SharedArrayBuffer', async () => { - const source = (await readFile(installed('isosurface/marching-cubes-worker.js'), 'utf8')) - .replace(/^import .*\n/, '') - const replies: { message: { ok: boolean; code?: string; data_buffer: ArrayBuffer }; transfer: ArrayBuffer[] }[] = [] - const context = { - SharedArrayBuffer: undefined, - preflight_marching_cubes: () => ({ total_bytes: 12 }), - marching_cubes_typed: () => ({ positions: new Float32Array(3), normals: new Float32Array(3), indices: new Uint32Array(3) }), - postMessage: (message: (typeof replies)[number]['message'], transfer: ArrayBuffer[]) => replies.push({ message, transfer }), - onmessage: (_event: unknown) => {}, - } - runInNewContext(source, context) - const data = new Float64Array(8) - const grid = { data, dims: [2, 2, 2], order: 'z_fastest' } - context.onmessage({ data: { job_id: 1, grid, iso_value: 0 } }) - assert.equal(replies[0].message.ok, true) - assert.equal(replies[0].message.data_buffer, data.buffer) - assert.ok(replies[0].transfer.includes(data.buffer)) - context.onmessage({ data: { job_id: 2, grid, iso_value: 0, options: { geometry_memory_budget_bytes: 0 } } }) - assert.equal(replies[1].message.ok, false) - assert.equal(replies[1].message.code, 'geometry-memory-budget') - assert.equal(replies[1].message.data_buffer, data.buffer) - assert.ok(replies[1].transfer.includes(data.buffer)) -}) - -test('Arcball restore repairs stale orientation after position and up were already assigned', async () => { - const { apply_arcball_camera_pose } = await import(installed('scene/arcball-runtime.js').href) - const { ArcballControls } = createRequire(realpathSync(installed('scene/arcball-runtime.js')))('three/examples/jsm/controls/ArcballControls.js') - const camera = new three.PerspectiveCamera() - camera.position.set(4, 3, 8) - const controls = new ArcballControls(camera, null) - const savedQuaternion = camera.quaternion.clone() - camera.position.set(-4, 8, -3) - camera.up.set(0, 0, 1) - controls.update() - assert.ok(1 - Math.abs(savedQuaternion.dot(camera.quaternion)) > 0.01) - // Reproduce declarative setters restoring fields before the Arcball effect. - camera.position.set(4, 3, 8) - camera.up.set(0, 1, 0) - assert.equal(apply_arcball_camera_pose(controls, { position: [4, 3, 8], up: [0, 1, 0], target: [0, 0, 0] }), true) - assert.ok(1 - Math.abs(savedQuaternion.dot(camera.quaternion)) < 1e-12) - const direction = camera.getWorldDirection(new three.Vector3()) - const expectedDirection = camera.position.clone().negate().normalize() - assert.ok(direction.distanceTo(expectedDirection) < 1e-12) -}) - -test('Arcball target-only commands and orthographic zoom preserve exact no-op live feedback', async () => { - const { apply_arcball_camera_pose } = await import(installed('scene/arcball-runtime.js').href) - const { ArcballControls } = createRequire(realpathSync(installed('scene/arcball-runtime.js')))('three/examples/jsm/controls/ArcballControls.js') - const camera = new three.OrthographicCamera(-5, 5, 5, -5) - camera.position.set(4, 3, 8) - const controls = new ArcballControls(camera, null) - assert.equal(apply_arcball_camera_pose(controls, { target: [2, -1, 0], zoom: 2.5 }), true) - assert.deepEqual(controls._gizmos.position.toArray(), [2, -1, 0]) - assert.equal(camera.zoom, 2.5) - const expected = camera.clone() - expected.lookAt(2, -1, 0) - assert.ok(1 - Math.abs(expected.quaternion.dot(camera.quaternion)) < 1e-12) - - // A rolled/panned live pose, including the equivalent negative quaternion, - // must not be rewritten when gesture-end bindings echo it back. - const roll = new three.Quaternion().setFromAxisAngle(camera.getWorldDirection(new three.Vector3()), 0.7) - camera.up.applyQuaternion(roll) - controls.update() - camera.quaternion.set(-camera.quaternion.x, -camera.quaternion.y, -camera.quaternion.z, -camera.quaternion.w) - const before = camera.quaternion.toArray() - assert.equal(apply_arcball_camera_pose(controls, { - position: camera.position.toArray(), up: camera.up.toArray(), target: controls._gizmos.position.toArray(), zoom: camera.zoom, - }), false) - assert.deepEqual(camera.quaternion.toArray(), before) -}) diff --git a/frontend/matterviz-viewer/tests/vendor-normals.test.ts b/frontend/matterviz-viewer/tests/vendor-normals.test.ts deleted file mode 100644 index b61173e1..00000000 --- a/frontend/matterviz-viewer/tests/vendor-normals.test.ts +++ /dev/null @@ -1,167 +0,0 @@ -import assert from 'node:assert/strict' -import { realpathSync } from 'node:fs' -import { readFile } from 'node:fs/promises' -import { createRequire } from 'node:module' -import { dirname, resolve } from 'node:path' -import { fileURLToPath, pathToFileURL } from 'node:url' -import test from 'node:test' -import { createServer } from 'vite' - -// The optional directory also lets package maintenance validate the staging -// files before packing. CI always exercises the installed production package. -const installedDist = new URL('../node_modules/matterviz/dist/', import.meta.url) -const dist = process.env.MATTERVIZ_VENDOR_DIST - ? pathToFileURL(`${resolve(process.env.MATTERVIZ_VENDOR_DIST)}/`) - : installedDist -const require = createRequire(realpathSync(new URL('marching-cubes.js', installedDist))) -const three = require('three') -type Vec3 = [number, number, number] -type Lattice = [Vec3, Vec3, Vec3] - -const latticeMatrix = (lattice: Lattice) => new three.Matrix4().set( - lattice[0][0], lattice[1][0], lattice[2][0], 0, - lattice[0][1], lattice[1][1], lattice[2][1], 0, - lattice[0][2], lattice[1][2], lattice[2][2], 0, - 0, 0, 0, 1, -) - -const makeGrid = (dimensions: Vec3, sample: (point: Vec3) => number) => { - const [nx, ny, nz] = dimensions - const data = new Float64Array(nx * ny * nz) - for (let x = 0; x < nx; x++) for (let y = 0; y < ny; y++) for (let z = 0; z < nz; z++) { - data[z + nz * (y + ny * x)] = sample([x / (nx - 1) - 0.5, y / (ny - 1) - 0.5, z / (nz - 1) - 0.5]) - } - return { data, dimensions, order: 'z-fastest' } -} - -test('production isosurface geometry derives Cartesian normals from its final triangle winding', async (t) => { - const vite = await createServer({ - configFile: false, - server: { middlewareMode: true, watch: null, hmr: false }, - appType: 'custom', - optimizeDeps: { noDiscovery: true }, - resolve: { alias: { three: resolve(dirname(require.resolve('three')), 'three.module.js') } }, - }) - const load = (path: string) => vite.ssrLoadModule(`/@fs/${fileURLToPath(new URL(path, dist))}`) - try { - const { marching_cubes_typed } = await load('marching-cubes.js') - const { build_typed_geometry } = await load('isosurface/mesh-geometry.js') - const source = await readFile(new URL('isosurface/Isosurface.svelte', dist), 'utf8') - assert.match(source, /import \{ build_typed_geometry \} from ['"]\.\/mesh-geometry['"]/) - assert.match(source, /const geometry = build_typed_geometry\(result\)/) - assert.doesNotMatch(source, /function build_typed_geometry\(/, 'the component must use the tested production helper') - const options = { periodic: false, centered: true, interpolate: true, normals: true } - const planeGradient = new three.Vector3(1.1, 0.6, -0.4) - const plane = makeGrid([11, 14, 17], ([x, y, z]) => 0.5 + 1.1 * x + 0.6 * y - 0.4 * z) - const lattices: Record = { - orthogonal: [[4, 0, 0], [0, 4, 0], [0, 0, 4]], - rotated: [[0, 4, 0], [-4, 0, 0], [0, 0, 4]], - anisotropic: [[2, 0, 0], [0, 8, 0], [0, 0, 3]], - skewed: [[4, 0.5, -0.2], [1.5, 3, 0.4], [-0.7, 0.8, 5]], - reflected: [[-4, 0, 0], [0, 4, 0], [0, 0, 4]], - } - for (const [name, lattice] of Object.entries(lattices)) { - await t.test(`${name} lattice matches an analytic plane and preserves face orientation`, () => { - const result = marching_cubes_typed(plane, 0.43, lattice, options) - const positions = result.positions.slice() - const indices = result.indices.slice() - const geometry = build_typed_geometry(result) - assert.ok(geometry) - try { - const normal = geometry.getAttribute('normal') - assert.ok(normal.count > 100, 'exercise the real marching-cubes mesh') - assert.equal(normal.array, result.normals, 'reuse the worker normal allocation within its memory budget') - assert.equal(geometry.getAttribute('position').array, result.positions) - assert.deepEqual(result.positions, positions, 'lighting must not move the scientific surface') - assert.deepEqual(geometry.index.array, indices, 'lighting must not change culling or transparent pass order') - const transform = latticeMatrix(lattice) - // A reflected lattice reverses the existing triangle winding. Match - // that orientation, as the legacy geometry-normal path already does. - const expected = planeGradient.clone().negate() - .applyMatrix3(new three.Matrix3().getNormalMatrix(transform)) - .multiplyScalar(Math.sign(transform.determinant())).normalize() - for (let vertex = 0; vertex < normal.count; vertex++) { - const actual = new three.Vector3().fromBufferAttribute(normal, vertex) - assert.ok(Math.abs(actual.length() - 1) < 1e-6, `${name}: normal must be finite and unit length`) - assert.ok(actual.dot(expected) > 1 - 1e-6, `${name}: vertex ${vertex} must point along the physical plane normal`) - } - } finally { - geometry.dispose() - } - }) - } - - await t.test('smooth closed density surface remains smooth and rotates with its geometry', () => { - const grid = makeGrid([25, 25, 25], ([x, y, z]) => Math.exp(-18 * (x * x + y * y + z * z))) - const baselineResult = marching_cubes_typed(grid, 0.3, lattices.orthogonal, options) - const endpointNormals = baselineResult.normals.slice() - const baseline = build_typed_geometry(baselineResult) - assert.ok(baseline) - try { - const baseNormal = baseline.getAttribute('normal') - const basePosition = baseline.getAttribute('position') - const errors = [] - const endpointErrors = [] - for (let vertex = 0; vertex < baseNormal.count; vertex++) { - const actual = new three.Vector3().fromBufferAttribute(baseNormal, vertex) - const radial = new three.Vector3().fromBufferAttribute(basePosition, vertex).normalize() - errors.push(Math.acos(Math.min(1, actual.dot(radial))) * 180 / Math.PI) - const endpointNormal = new three.Vector3().fromArray(endpointNormals, vertex * 3) - endpointErrors.push(Math.acos(Math.min(1, endpointNormal.dot(radial))) * 180 / Math.PI) - } - errors.sort((left, right) => left - right) - endpointErrors.sort((left, right) => left - right) - assert.ok(errors.at(-1)! < 6, 'the coarse 25³ sphere must retain smooth, outward-facing normals') - for (const percentile of [0.5, 0.95]) { - const index = Math.floor(errors.length * percentile) - assert.ok(errors[index] < endpointErrors[index] * 0.85, 'smooth vertex normals must improve on grid-endpoint normals, not add faceting') - } - - for (const [name, lattice] of Object.entries(lattices)) { - if (name === 'orthogonal') continue - const result = marching_cubes_typed(grid, 0.3, lattice, options) - const geometry = build_typed_geometry(result) - assert.ok(geometry) - try { - const normal = geometry.getAttribute('normal') - assert.equal(normal.count, baseNormal.count) - assert.deepEqual(geometry.index.array, baseline.index.array) - const transform = latticeMatrix(lattice) - const normalMatrix = new three.Matrix3().getNormalMatrix(transform) - for (let vertex = 0; vertex < normal.count; vertex++) { - const expected = new three.Vector3().fromBufferAttribute(baseNormal, vertex) - .applyMatrix3(normalMatrix).multiplyScalar(Math.sign(transform.determinant())).normalize() - const actual = new three.Vector3().fromBufferAttribute(normal, vertex) - assert.ok(actual.dot(expected) > 1 - 1e-6, `${name}: smooth normal ${vertex} must follow the affine geometry transform`) - } - } finally { - geometry.dispose() - } - } - } finally { - baseline.dispose() - } - }) - - await t.test('reversed winding, missing gradient buffers, and empty meshes remain well-defined', () => { - for (const [indices, expectedZ] of [[new Uint32Array([0, 1, 2]), 1], [new Uint32Array([0, 2, 1]), -1]] as const) { - const geometry = build_typed_geometry({ - positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]), - normals: new Float32Array(0), - indices, - }) - assert.ok(geometry) - try { - assert.deepEqual(Array.from(geometry.getAttribute('normal').array), [0, 0, expectedZ, 0, 0, expectedZ, 0, 0, expectedZ]) - assert.ok(Number.isFinite(geometry.boundingSphere.radius)) - } finally { - geometry.dispose() - } - } - assert.equal(build_typed_geometry({ positions: new Float32Array(0), indices: new Uint32Array(0) }), null) - assert.equal(build_typed_geometry({ positions: new Float32Array(9), indices: new Uint32Array(0) }), null) - }) - } finally { - await vite.close() - } -}) diff --git a/frontend/matterviz-viewer/tests/vendor-upstream.test.ts b/frontend/matterviz-viewer/tests/vendor-upstream.test.ts deleted file mode 100644 index 685c8443..00000000 --- a/frontend/matterviz-viewer/tests/vendor-upstream.test.ts +++ /dev/null @@ -1,183 +0,0 @@ -import assert from 'node:assert/strict' -import { readFile } from 'node:fs/promises' -import test from 'node:test' -import { gzipSync } from 'node:zlib' -import { createServer, type ViteDevServer } from 'vite' - -let server: ViteDevServer -let parser: any -let sampling: any -let marching: any -let math: any -let binary: any -let compression: any - -test.before(async () => { - server = await createServer({ - appType: 'custom', logLevel: 'error', - server: { middlewareMode: true, watch: null }, - optimizeDeps: { noDiscovery: true }, - }) - const load = (path: string) => server.ssrLoadModule(`/node_modules/matterviz/dist/${path}`) - ;[parser, sampling, marching, math, binary, compression] = await Promise.all([ - load('isosurface/parse.js'), load('isosurface/sampling.js'), load('marching-cubes.js'), - load('math.js'), load('io/is-binary.js'), load('io/decompress.js'), - ]) -}) -test.after(async () => { await server?.close() }) - -const cube = (values: (number | string)[], header = '1 1 2 3', orbital = '') => [ - 'Upstream regression', '2 by 2 by 2 finite grid', header, - '-2 1 0 0', '-2 0 1 0', '-2 0 0 1', '1 1 1.5 2 3', - ...(orbital ? [orbital] : []), values.join(' '), '', -].join('\n') -const values = [1, 2, 3, 4, 5, 6, 7, 8] -const chgcar = (body: string) => [ - 'Hydrogen density', '1', '2 0 0', '0 2 0', '0 0 2', 'H', '1', - 'Direct', '0 0 0', '', '2 2 2', body, '', -].join('\n') - -test('single-field Cube preserves samples, finite voxel spacing and atom coordinates', () => { - const parsed = parser.parse_cube(cube(values), { periodic: false }) - assert.deepEqual(Array.from(parsed.volumes[0].grid.data), values) - assert.deepEqual(parsed.volumes[0].lattice, [[1, 0, 0], [0, 1, 0], [0, 0, 1]]) - assert.deepEqual(parsed.structure.sites[0].xyz, [0.5, 0, 0]) - assert.deepEqual(parsed.structure.sites[0].abc, [0.5, 0, 0]) - assert.deepEqual(parser.parse_cube(cube(values), { periodic: true }).volumes[0].lattice, - [[2, 0, 0], [0, 2, 0], [0, 0, 2]]) -}) - -test('Cube NVAL and orbital headers cannot silently mix multiple fields', () => { - const interleaved = values.flatMap(value => [value, value + 100]) - assert.throws(() => parser.parse_cube(cube(interleaved, '1 1 2 3 2')), /single-field/) - assert.throws(() => parser.parse_cube(cube(interleaved, '-1 1 2 3', '2 5 6')), /single-field/) - assert.deepEqual(Array.from(parser.parse_cube(cube(values, '-1 1 2 3', '1 5')).volumes[0].grid.data), values) -}) - -test('truncated Cube and CHGCAR charge fields fail instead of becoming zero-filled data', () => { - assert.throws(() => parser.parse_cube(cube(values.slice(0, 4))), /expected 8.*got 4/) - assert.throws(() => parser.parse_chgcar(chgcar('1 2 3 4')), /expected 8.*got 4/) - const parsed = parser.parse_chgcar(chgcar(values.join(' ') + '\n\n2 2 2\n1 2 3')) - assert.equal(parsed.volumes.length, 1, 'retain complete charge density, omit partial magnetization') - assert.deepEqual(Array.from(parsed.volumes[0].grid.data), values.map(value => value / 8)) -}) - -test('recognized malformed files report their own filename and unknown formats still return null', () => { - assert.throws(() => parser.parse_volumetric_file(cube([1]), 'broken.cub'), /broken\.cub.*expected 8/) - assert.throws(() => parser.parse_volumetric_file(cube(values, '1 1 2 3 2'), 'other.cube.gz'), - error => error instanceof Error && /other\.cube\.gz.*single-field/.test(error.message) && !/broken/.test(error.message)) - assert.throws(() => parser.parse_volumetric_file(cube([1])), /expected 8/) - assert.equal(parser.parse_volumetric_file('not a volumetric file', 'notes.txt'), null) -}) - -test('impossible grid dimensions fail before a large typed-array allocation', () => { - for (const dims of ['600', '0', '1.5', '9007199254740992']) { - const content = cube(values).replace('-2 1 0 0', `-${dims} 1 0 0`) - .replace('-2 0 1 0', `-${dims} 0 1 0`).replace('-2 0 0 1', `-${dims} 0 0 1`) - assert.throws(() => parser.parse_cube(content), /not a valid point count|bytes remain/) - } - assert.throws(() => parser.parse_cube(cube(values).replace('1 1 2 3\n', '1000 1 2 3\n')), /ends before atom/) - assert.throws(() => parser.parse_cube(cube(values).replace('-2 0 1 0', '-2 1 0 0')), /singular/) -}) - -test('Fortran exponents are accepted and non-finite or invalid field values are rejected', () => { - assert.deepEqual(Array.from(parser.parse_cube(cube(values.map(value => `${value}D+0`))).volumes[0].grid.data), values) - for (const invalid of ['NaN', 'Infinity', '1e999', 'not-a-number']) { - assert.throws(() => parser.parse_cube(cube([1, invalid, ...values.slice(2)])), /Invalid volumetric value|truncated/) - } -}) - -test('CRLF and tab-heavy XYZ text remains text while NUL and binary bytes remain binary', () => { - assert.equal(binary.is_binary('2\r\n\r\nH\t0\t0\t0\r\nH\t1\t0\t0\r\n'), false) - assert.equal(binary.is_binary('text\0text'), true) - assert.equal(binary.is_binary('\u0001\u0002\u00ff'), true) -}) - -test('decompression preserves valid content and stops an inflated stream at its byte limit', async () => { - const content = cube(values) - const gz = gzipSync(content) - const buffer = gz.buffer.slice(gz.byteOffset, gz.byteOffset + gz.byteLength) - assert.equal(await compression.decompress_data(buffer, 'gzip'), content) - const chunks = () => new ReadableStream({ - start(controller) { controller.enqueue(new Uint8Array(4)); controller.enqueue(new Uint8Array(4)); controller.close() }, - }) - assert.equal((await new Response(chunks().pipeThrough(compression.inflation_limiter('gzip', 8))).arrayBuffer()).byteLength, 8) - await assert.rejects(new Response(chunks().pipeThrough(compression.inflation_limiter('gzip', 7))).arrayBuffer(), /7-byte inflated limit/) -}) - -const planeVolume = (periodic: boolean, lattice = [[20, 0, 0], [0, 13, 0], [0, 0, 8]]) => { - const dims = [81, 17, 13] - const data = Float64Array.from({ length: dims[0] * dims[1] * dims[2] }, (_, idx) => - Math.floor(idx / (dims[1] * dims[2])) / (periodic ? dims[0] : dims[0] - 1)) - return { grid: { data, dimensions: dims, order: 'z-fastest' }, grid_dims: dims, - lattice, origin: [3, -2, 1], periodic, - data_range: { min: 0, max: 1, mean: 0.5, abs_max: 1 } } -} -const meshFractions = (volume: any, prepared: any) => { - const mesh = marching.marching_cubes_typed(prepared.grid, 0.37, prepared.lattice, - { periodic: prepared.periodic, centered: false, interpolate: true, normals: false }) - assert.ok(mesh.positions.length > 0) - const to_frac = math.create_cart_to_frac(volume.lattice) - return Array.from({ length: mesh.positions.length / 3 }, (_, idx) => to_frac( - [0, 1, 2].map(axis => mesh.positions[idx * 3 + axis] + prepared.origin[axis] - volume.origin[axis]))) -} - -test('bounded geometry preparation preserves an analytic plane in orthogonal and skew cells', () => { - for (const lattice of [[[20, 0, 0], [0, 13, 0], [0, 0, 8]], [[20, 0, 0], [3, 13, 0], [-2, 1, 8]]]) { - const volume = planeVolume(false, lattice) - const prepared = sampling.prepare_geometry_grid(volume, null, { max_points: 64 }) - assert.ok(prepared.grid.data.length <= 64) - for (const [x] of meshFractions(volume, prepared)) assert.ok(Math.abs(x - 0.37) < 1e-6, `plane at ${x}, expected 0.37`) - assert.equal(volume.grid.data.length, 81 * 17 * 13, 'source data remains untouched') - } -}) - -test('managed grids retain buffer ownership and periodic marching uses physical voxel spacing', () => { - for (const periodic of [false, true]) { - const volume = planeVolume(periodic) - const prepared = sampling.prepare_geometry_grid(volume, null, { preserve_grid: true }) - assert.equal(prepared.grid, volume.grid) - assert.equal(prepared.grid.data, volume.grid.data) - assert.equal(prepared.periodic, periodic) - const interior = meshFractions(volume, prepared).filter(([x]: number[]) => x < 0.8) - assert.ok(interior.length > 0) - for (const [x] of interior) assert.ok(Math.abs(x - 0.37) < 1e-6) - } -}) - -test('integer tiling and fractional ranges sample the same physical periodic field', () => { - const volume = planeVolume(true) - const tiled = sampling.prepare_geometry_grid(volume, null, { tiling: [2, 1, 1], max_points: 30_000 }) - const ranged = sampling.prepare_geometry_grid(volume, [[0, 2], [0, 1], [0, 1]], { max_points: 30_000 }) - assert.deepEqual(tiled, ranged) - const points = meshFractions(volume, tiled) - for (const cell of [0, 1]) { - const plane = points.filter(([x]: number[]) => x >= cell && x < cell + 0.7) - assert.ok(plane.length > 0) - for (const [x] of plane) assert.ok(Math.abs(x - cell - 0.37) < 1e-6) - } -}) - -test('periodic buffer reuse closes boundary cells without cell-spanning triangles', () => { - const volume = planeVolume(true) - const prepared = sampling.prepare_geometry_grid(volume, null, { preserve_grid: true }) - const mesh = marching.marching_cubes_typed(prepared.grid, 0.37, prepared.lattice, - { periodic: prepared.periodic, centered: false, interpolate: true, normals: false }) - assert.ok(mesh.indices.length > 0) - const lengths = [20, 13, 8] - for (let offset = 0; offset < mesh.indices.length; offset += 3) { - for (let axis = 0; axis < 3; axis++) { - const coords = [0, 1, 2].map(corner => mesh.positions[mesh.indices[offset + corner] * 3 + axis]) - assert.ok(Math.min(...coords) >= -1e-6 && Math.max(...coords) <= lengths[axis] + 1e-6) - assert.ok(Math.max(...coords) - Math.min(...coords) <= lengths[axis] / volume.grid_dims[axis] + 1e-5, - 'a wrapped edge must not connect opposite faces of the displayed cell') - } - } -}) - -test('the rendered isosurface uses the tested preparation and boundary mode', async () => { - const component = await readFile(new URL('../node_modules/matterviz/dist/isosurface/Isosurface.svelte', import.meta.url), 'utf8') - assert.match(component, /prepare_geometry_grid\(vol, effective_range\(vol\)/) - assert.match(component, /periodic: prepared\.periodic/) - assert.doesNotMatch(component, /downsample_grid\(|tile_volumetric_data\(/) -}) diff --git a/frontend/matterviz-viewer/tests/vendor.test.ts b/frontend/matterviz-viewer/tests/vendor.test.ts deleted file mode 100644 index 1035f076..00000000 --- a/frontend/matterviz-viewer/tests/vendor.test.ts +++ /dev/null @@ -1,216 +0,0 @@ -import assert from 'node:assert/strict' -import { readFile } from 'node:fs/promises' -import { fileURLToPath } from 'node:url' -import test from 'node:test' -import ts from 'typescript' -import type { VolumetricData } from 'matterviz/isosurface' -import { createServer } from 'vite' - -const installed = (path: string): URL => new URL(`../node_modules/matterviz/dist/${path}`, import.meta.url) - -test('vendored MatterViz declarations expose the bindable camera API', async () => { - const [sceneDeclaration, structureDeclaration, cameraDeclaration, cameraModeDeclaration, arcballImplementation] = await Promise.all([ - readFile(installed('structure/StructureScene.svelte.d.ts'), 'utf8'), - readFile(installed('structure/index.d.ts'), 'utf8'), - readFile(installed('scene/SceneCamera.svelte.d.ts'), 'utf8'), - readFile(installed('scene/camera-controls.svelte.d.ts'), 'utf8'), - readFile(installed('scene/ArcballControls.svelte'), 'utf8'), - ]) - assert.match(sceneDeclaration, /camera_control_mode\?: CameraControlMode;/) - assert.match(sceneDeclaration, /camera_up\?: Vec3;/) - assert.match(sceneDeclaration, /camera_zoom\?: number;/) - const componentDeclaration = sceneDeclaration.match(/declare const StructureScene:.*;/)?.[0] ?? '' - assert.match(componentDeclaration, /"camera_up"/) - assert.match(componentDeclaration, /"camera_zoom"/) - assert.match(structureDeclaration, /camera_up\?: Vec3;/) - assert.match(structureDeclaration, /camera_zoom\?: number;/) - assert.match(cameraDeclaration, /camera_control_mode\?: CameraControlMode;/) - assert.match(cameraModeDeclaration, /export type CameraControlMode = `orbit` \| `arcball`;/) - assert.match(arcballImplementation, /controls\.enableAnimations = false/) - assert.match(arcballImplementation, /let interaction_active = \$state\(false\)/) -}) - -test('vendored MatterViz exposes and threads ordered measurement interaction props', async () => { - const [ - structureDeclaration, - viewportDeclaration, - sceneDeclaration, - structureImplementation, - viewportImplementation, - sceneImplementation, - structureIndex, - ] = await Promise.all([ - readFile(installed('structure/Structure.svelte.d.ts'), 'utf8'), - readFile(installed('structure/StructureViewport.svelte.d.ts'), 'utf8'), - readFile(installed('structure/StructureScene.svelte.d.ts'), 'utf8'), - readFile(installed('structure/Structure.svelte'), 'utf8'), - readFile(installed('structure/StructureViewport.svelte'), 'utf8'), - readFile(installed('structure/StructureScene.svelte'), 'utf8'), - readFile(installed('structure/index.d.ts'), 'utf8'), - ]) - - const propDeclarations = [ - /show_atom_tooltip\?: boolean;/, - /measure_selection_policy\?: MeasureSelectionPolicy;/, - /measure_geometry\?: MeasureGeometry;/, - /on_selected_bond_context\?: \(detail: SelectedBondContext\) => void;/, - ] - for (const declaration of [structureDeclaration, viewportDeclaration, sceneDeclaration]) { - for (const prop of propDeclarations) assert.match(declaration, prop) - } - - for (const prop of [ - 'show_atom_tooltip', - 'measure_selection_policy', - 'measure_geometry', - 'on_selected_bond_context', - ]) { - assert.ok(structureImplementation.includes(` ${prop},`)) - assert.ok(viewportImplementation.includes(`{${prop}}`)) - } - - assert.match(structureIndex, /export type MeasureGeometry = `combinatorial` \| `ordered`;/) - assert.match(structureIndex, /export type SelectedBondContext = \{/) - assert.match(structureIndex, /displayed_site_indices: \[number, number\];/) - assert.match(structureIndex, /source_site_indices: \[number, number\];/) - assert.match(structureIndex, /bond_order\?: BondOrder;/) - assert.match(structureIndex, /cell_shift\?: Vec3;/) - assert.match(structureIndex, /client_x: number;/) - assert.match(structureIndex, /client_y: number;/) - assert.ok(structureIndex.includes("export * from './measure';")) - - assert.ok(sceneImplementation.includes('show_atom_tooltip = true')) - assert.ok(sceneImplementation.includes('measure_geometry = `combinatorial`')) - assert.ok(sceneImplementation.includes('{#if show_atom_tooltip && hovered_site')) - assert.ok(sceneImplementation.includes('add(`hover`, hovered_site, hovered_idx, `white`)')) - assert.ok(sceneImplementation.includes('measure.next_measured_sites(')) - assert.ok(sceneImplementation.includes('measure.bond_angle(')) - assert.ok(sceneImplementation.includes('measure.dihedral_angle(')) - assert.ok(sceneImplementation.includes('distance_measurement(measured_sites[0], measured_sites[1])')) - assert.ok(sceneImplementation.includes('{@render ordered_angle_measurement(')) - assert.ok(sceneImplementation.includes('{@render ordered_dihedral_measurement(')) -}) - -test('vendored MatterViz only emits bond context for a selected visible bond', async () => { - const scene = await readFile(installed('structure/StructureScene.svelte'), 'utf8') - - assert.ok(scene.includes('(measure_mode !== `distance` && measure_mode !== `angle`)')) - assert.ok(scene.includes('measured_sites.length !== 2')) - assert.ok(scene.includes('(site_idx != null && !measured_sites.includes(site_idx))')) - assert.ok(scene.includes('!selected_context_bond')) - assert.ok(scene.includes('const exact = bonds_to_render.find(')) - assert.ok(scene.includes('const source_matches =')) - assert.ok(scene.includes('measure.positions_match(bond.pos_1, selected_site_a.xyz)')) - assert.ok(scene.includes('measure.positions_match(bond.pos_2, selected_site_b.xyz)')) - assert.ok(scene.includes('measure.positions_match(bond.pos_1, selected_site_b.xyz)')) - assert.ok(scene.includes('measure.positions_match(bond.pos_2, selected_site_a.xyz)')) - assert.ok(scene.includes('function suppress_selected_bond_pointerdown(')) - assert.ok(scene.includes('native_event.button !== 2')) - const suppressionStart = scene.indexOf('function suppress_selected_bond_pointerdown(') - const suppressionEnd = scene.indexOf('const handle_atom_pointerdown', suppressionStart) - const suppression = scene.slice(suppressionStart, suppressionEnd) - assert.ok(suppression.includes('native_event.preventDefault?.()')) - assert.ok(suppression.includes('native_event.stopPropagation?.()')) - assert.ok(suppression.includes('native_event.stopImmediatePropagation?.()')) - assert.ok(suppression.includes('event.preventDefault?.()')) - assert.ok(suppression.includes('event.stopPropagation?.()')) - assert.ok(suppression.includes('event.stopImmediatePropagation?.()')) - assert.ok(scene.includes('if ((event.nativeEvent ?? event).button !== 0) return')) - assert.ok(scene.includes('oncontextmenu: (event: BondContextMenuEvent) =>')) - assert.ok(scene.includes('emit_selected_bond_context(event, site_idx)')) - assert.ok(scene.includes('{#if selected_context_bond}')) - assert.ok(scene.includes('suppress_selected_bond_pointerdown(event)')) - assert.ok(scene.includes('emit_selected_bond_context(event)')) - assert.ok(scene.includes('measure_mode === `edit-bonds` && bond_context_menu')) -}) - -test('vendored package exports interaction helpers and types from the public entry point', () => { - const declarationPath = fileURLToPath(installed('index.d.ts')) - const program = ts.createProgram([declarationPath], { - allowJs: true, - module: ts.ModuleKind.ESNext, - moduleResolution: ts.ModuleResolutionKind.Bundler, - noEmit: true, - skipLibCheck: false, - target: ts.ScriptTarget.ES2022, - }) - const source = program.getSourceFile(declarationPath) - assert.ok(source) - const moduleSymbol = program.getTypeChecker().getSymbolAtLocation(source) - assert.ok(moduleSymbol) - const exported = program.getTypeChecker().getExportsOfModule(moduleSymbol) - const exportedNames = new Set(exported.map((symbol) => symbol.name)) - for (const name of [ - 'CameraControlMode', - 'MeasureGeometry', - 'MeasureSelectionPolicy', - 'SelectedBondContext', - 'bond_angle', - 'dihedral_angle', - 'next_measured_sites', - ]) { - assert.ok(exportedNames.has(name), `expected MatterViz to export ${name}`) - } -}) - -test('vendored Arcball package retains r19 volume release lifecycle', async () => { - const [geometry, isosurface, scene, viewport] = await Promise.all([ - readFile(installed('isosurface/geometry.js'), 'utf8'), - readFile(installed('isosurface/Isosurface.svelte'), 'utf8'), - readFile(installed('structure/StructureScene.svelte'), 'utf8'), - readFile(installed('structure/StructureViewport.svelte'), 'utf8'), - ]) - assert.match(geometry, /const release_epochs = new WeakMap\(\)/) - assert.match(geometry, /release_isosurface_geometry/) - assert.match(isosurface, /release_isosurface_geometry/) - assert.match(scene, /on_geometry_error\?: \(message: string\) => void/) - assert.match(scene, /\{on_geometry_error\}/) - assert.match(viewport, /on_geometry_error\?: \(message: string\) => void/) - assert.match(viewport, /\{on_geometry_error\}/) -}) - -test('vendored MatterViz preserves explicitly absolute volume origins', async () => { - const [declaration, implementation] = await Promise.all([ - readFile(installed('isosurface/types.d.ts'), 'utf8'), - readFile(installed('isosurface/Isosurface.svelte'), 'utf8'), - ]) - assert.match(declaration, /origin_mode\?: `relative-first` \| `absolute`;/) - assert.equal(implementation.match(/volume_reference_origin\(all_volumes\)/g)?.length, 3) -}) - -test('absolute and relative-first scene coordinates sample the same physical point', async () => { - const vite = await createServer({ - configFile: false, - server: { middlewareMode: true, watch: null }, - appType: 'custom', - optimizeDeps: { noDiscovery: true }, - }) - try { - const { create_volume_sampler, volume_reference_origin } = await vite.ssrLoadModule( - '/node_modules/matterviz/dist/isosurface/sampling.js', - ) - const base: VolumetricData = { - grid: [ - [[0, 0], [0, 0]], - [[4, 4], [4, 4]], - ], - grid_dims: [2, 2, 2], - lattice: [[2, 0, 0], [0, 2, 0], [0, 0, 2]], - origin: [10, 20, 30], - data_range: { min: 0, max: 4, abs_max: 4, mean: 2 }, - periodic: false, - } - const sample = create_volume_sampler(base, { out_of_bounds: 'fallback' }) - - const absolute = { ...base, origin_mode: 'absolute' as const } - const absolute_ref = volume_reference_origin([absolute]) - assert.deepEqual(absolute_ref, [0, 0, 0]) - assert.equal(sample([11 + absolute_ref[0], 20, 30]), 2) - - const relative_ref = volume_reference_origin([base]) - assert.deepEqual(relative_ref, [10, 20, 30]) - assert.equal(sample([1 + relative_ref[0], relative_ref[1], relative_ref[2]]), 2) - } finally { - await vite.close() - } -}) diff --git a/frontend/matterviz-viewer/tests/volume-cache.test.ts b/frontend/matterviz-viewer/tests/volume-cache.test.ts deleted file mode 100644 index 1f9e8a74..00000000 --- a/frontend/matterviz-viewer/tests/volume-cache.test.ts +++ /dev/null @@ -1,153 +0,0 @@ -import assert from 'node:assert/strict' -import test from 'node:test' - -import { - compact_volume_cache, - orbital_visibility, - type VolumeCacheState, -} from '../src/volume-cache.ts' -import { loaded_orbital_volume_index } from '../src/orbital.ts' - -const volume = (name: string, buffer = new ArrayBuffer(8)) => ({ - name, - grid: { data: new Float64Array(buffer), dimensions: [1, 1, 1], order: 'x-fastest' }, -}) - -const state = ( - volumes: ReturnType[], - entries: VolumeCacheState>['entries'], - layers: VolumeCacheState>['layers'], - active_volume_idx = 0, -): VolumeCacheState> => ({ volumes, entries, layers, active_volume_idx }) - -test('switching orbitals releases the previous orbital and forces a later backend request', () => { - const orbital12 = volume('MO 12') - const orbital13 = volume('MO 13') - const switched = compact_volume_cache(state( - [orbital12, orbital13], - [ - { path: '/api/orbital', role: 'orbital', orbitalIndex: 12 }, - { path: '/api/orbital', role: 'orbital', orbitalIndex: 13 }, - ], - orbital_visibility([ - { volume_idx: 0, visible: true }, - { volume_idx: 1, visible: false }, - ], [ - { path: '/api/orbital', role: 'orbital', orbitalIndex: 12 }, - { path: '/api/orbital', role: 'orbital', orbitalIndex: 13 }, - ], 1), - 1, - )) - - assert.deepEqual(switched.volumes, [orbital13]) - assert.deepEqual(switched.released_volumes, [orbital12]) - assert.equal(switched.active_volume_idx, 0) - assert.equal(switched.layers[0]?.volume_idx, 0) - assert.equal(loaded_orbital_volume_index(switched.entries, 12), undefined) - assert.equal(loaded_orbital_volume_index(switched.entries, 13), 0) -}) - -test('orbital switching preserves visible non-orbital data but drops hidden orbitals', () => { - const density = volume('density') - const oldOrbital = volume('MO 5') - const newOrbital = volume('MO 6') - const entries = [ - { path: 'density.cube', role: 'density' }, - { path: '/api/orbital', role: 'orbital', orbitalIndex: 5 }, - { path: '/api/orbital', role: 'orbital', orbitalIndex: 6 }, - ] - const layers = orbital_visibility([ - { volume_idx: 0, visible: true }, - { volume_idx: 1, visible: true }, - { volume_idx: 2, visible: false }, - ], entries, 2) - assert.equal(layers[0]?.visible, true) - - const compacted = compact_volume_cache(state( - [density, oldOrbital, newOrbital], - entries, - layers, - 2, - )) - assert.deepEqual(compacted.volumes, [density, newOrbital]) - assert.deepEqual(compacted.released_volumes, [oldOrbital]) - assert.equal(compacted.active_volume_idx, 1) -}) - -test('retains hidden color and slice sources while referenced, then releases an orphaned source', () => { - const surface = volume('surface') - const colors = volume('colors') - const slice = volume('slice') - const initial = state( - [surface, colors, slice], - [ - { path: 'surface.cube' }, - { path: 'colors.cube' }, - { path: 'slice.cube' }, - ], - [ - { volume_idx: 0, color_volume_idx: 1, visible: true }, - { volume_idx: 1, visible: false }, - { volume_idx: 2, visible: false }, - ], - 2, - ) - const retained = compact_volume_cache(initial, { retain_active_volume: true }) - assert.deepEqual(retained.volumes, [surface, colors, slice]) - - const deletedOwner = compact_volume_cache(initial, { - remove_indices: [0], - retain_active_volume: true, - }) - assert.deepEqual(deletedOwner.volumes, [slice]) - assert.deepEqual(deletedOwner.released_volumes, [surface, colors]) - assert.equal(deletedOwner.active_volume_idx, 0) -}) - -test('pruning reindexes surface and color-volume references deterministically', () => { - const hidden = volume('hidden') - const colors = volume('colors') - const surface = volume('surface') - const compacted = compact_volume_cache(state( - [hidden, colors, surface], - [{ path: 'hidden' }, { path: 'colors' }, { path: 'surface' }], - [ - { volume_idx: 0, visible: false }, - { volume_idx: 1, visible: false }, - { volume_idx: 2, color_volume_idx: 1, visible: true }, - ], - 2, - )) - assert.deepEqual(compacted.volumes, [colors, surface]) - assert.deepEqual(compacted.old_to_new, new Map([[1, 0], [2, 1]])) - assert.deepEqual(compacted.layers, [ - { volume_idx: 0, visible: false }, - { volume_idx: 1, color_volume_idx: 0, visible: true }, - ]) - assert.equal(compacted.active_volume_idx, 1) -}) - -test('replacement removes the old SharedArrayBuffer view and counts shared backing once', (t) => { - if (typeof SharedArrayBuffer === 'undefined') { - t.skip('SharedArrayBuffer is unavailable') - return - } - const shared = new SharedArrayBuffer(16) - const old = volume('old', shared) - const alias = volume('alias', shared) - const replacement = volume('replacement') - const compacted = compact_volume_cache(state( - [old, alias, replacement], - [{ path: 'old' }, { path: 'alias' }, { path: 'replacement' }], - [ - { volume_idx: 0, visible: false }, - { volume_idx: 1, visible: false }, - { volume_idx: 2, visible: true }, - ], - 2, - )) - assert.deepEqual(compacted.volumes, [replacement]) - assert.deepEqual(compacted.released_volumes, [old, alias]) - assert.equal(compacted.released_buffers.size, 1) - assert.ok(compacted.released_buffers.has(shared)) -}) diff --git a/frontend/matterviz-viewer/tests/volume-cube-equivalence.test.ts b/frontend/matterviz-viewer/tests/volume-cube-equivalence.test.ts index edcd7387..33a46328 100644 --- a/frontend/matterviz-viewer/tests/volume-cube-equivalence.test.ts +++ b/frontend/matterviz-viewer/tests/volume-cube-equivalence.test.ts @@ -9,18 +9,14 @@ let server: ViteDevServer let parse_cube: (content: string, options?: { periodic?: boolean }) => { volumes: VolumetricData[] } | null -let request_isosurface_geometry: ( - grid: VolumetricData['grid'], - isovalue: number, - lattice: VolumetricData['lattice'], - options?: { periodic?: boolean; centered?: boolean }, -) => Promise<{ positions: Float32Array }> +let create_volume_sampler: typeof import('matterviz/isosurface').create_volume_sampler test.before(async () => { - server = await createServer({ appType: 'custom', logLevel: 'silent', server: { middlewareMode: true } }) + server = await createServer({ appType: 'custom', logLevel: 'silent', server: { middlewareMode: true, watch: null, hmr: false } }) const parser = await server.ssrLoadModule('matterviz/isosurface') - parse_cube = parser.parse_cube - request_isosurface_geometry = parser.request_isosurface_geometry + const session = await server.ssrLoadModule('/src/session-fields.ts') + parse_cube = (content, options) => session.parse_session_cube(content, options?.periodic) + create_volume_sampler = parser.create_volume_sampler }) test.after(async () => { @@ -41,13 +37,7 @@ const assert_close = (actual: number, expected: number, message: string): void = } const grid_value = (volume: VolumetricData, x: number, y: number, z: number): number => { - const grid = volume.grid - if (Array.isArray(grid)) return grid[x]![y]![z]! - const [nx, ny, nz] = grid.dimensions - const index = grid.order === 'x-fastest' - ? x + nx * (y + ny * z) - : z + nz * (y + ny * x) - return grid.data[index]! + return volume.values[(x * volume.dims[1] + y) * volume.dims[2] + z] } test('periodic binary adapter is numerically equivalent to the MatterViz Cube parser', async () => { @@ -63,10 +53,10 @@ test('periodic binary adapter is numerically equivalent to the MatterViz Cube pa decoded.periodic_axes = [true, true, true] const binary = adapt_matterviz_volume(decoded) - assert.deepEqual(binary.grid_dims, cube.grid_dims) - for (let x = 0; x < binary.grid_dims[0]; x += 1) { - for (let y = 0; y < binary.grid_dims[1]; y += 1) { - for (let z = 0; z < binary.grid_dims[2]; z += 1) { + assert.deepEqual(binary.dims, cube.dims) + for (let x = 0; x < binary.dims[0]; x += 1) { + for (let y = 0; y < binary.dims[1]; y += 1) { + for (let z = 0; z < binary.dims[2]; z += 1) { assert_close(grid_value(binary, x, y, z), grid_value(cube, x, y, z), `grid[${x}][${y}][${z}]`) } } @@ -101,16 +91,8 @@ test('finite binary grid uses endpoint span and places a 2x2x2 half-isosurface a const finite = adapt_matterviz_volume(decoded) assert.deepEqual(finite.lattice, [[1, 0, 0], [0, 1, 0], [0, 0, 1]]) - const geometry = await request_isosurface_geometry( - finite.grid, - 0.5, - finite.lattice, - { periodic: false, centered: false }, - ) - assert.ok(geometry.positions.length > 0) - const xs = Array.from({ length: geometry.positions.length / 3 }, (_, index) => - geometry.positions[index * 3]!) - for (const x of xs) assert_close(x, 0.5, 'isosurface x') + const sample = create_volume_sampler(finite) + for (const y of [0, .5, 1]) for (const z of [0, .5, 1]) assert_close(sample([0.5, y, z]), 0.5, 'half-isovalue plane') const periodic = adapt_matterviz_volume({ ...decoded, periodic_axes: [true, true, true] }) assert.deepEqual(periodic.lattice, [[2, 0, 0], [0, 2, 0], [0, 0, 2]]) diff --git a/frontend/matterviz-viewer/tests/volume-mapping.test.ts b/frontend/matterviz-viewer/tests/volume-mapping.test.ts index d9cea565..12aec3d6 100644 --- a/frontend/matterviz-viewer/tests/volume-mapping.test.ts +++ b/frontend/matterviz-viewer/tests/volume-mapping.test.ts @@ -1,112 +1,31 @@ import assert from 'node:assert/strict' import test from 'node:test' -import { readFile } from 'node:fs/promises' -import { transpileModule, ScriptTarget } from 'typescript' -import { color_stop_interpolator } from 'matterviz/colors/stops' -import { apply_manifest_color_mapping } from '../src/volume-mapping.ts' -import { migrate_reps, remap_rep_sources } from '../src/reps.ts' -import { read_geometry_memory_budget } from '../src/volume.ts' +import { createServer } from 'vite' -const template = await readFile(new URL('../../../tests/fixtures/weak-interaction-vmd/IRIfill.vmd', import.meta.url), 'utf8') -const range = template.match(/mol scaleminmax top 1 ([-.\d]+) ([-.\d]+)/)!.slice(1).map(Number) as [number, number] -const midpoint = Number(template.match(/color scale midpoint ([.\d]+)/)![1]) -const entries = [ - { name: 'IRI', path: '/api/volume/1', colorMapping: { path: '/api/volume/2', range, - stops: [{ position: 0, color: '#0000ff' }, { position: midpoint, color: '#00ff00' }, { position: 1, color: '#ff0000' }] } }, - { name: 'sign(lambda2)rho', path: '/api/volume/2' }, -] -const layers = [{ volume_idx: 0, isovalue: 0.1, show_negative: false, visible: true, opacity: 1 }, { volume_idx: 1, visible: false }] - -test('maps IRI geometry by the separate signed field using the official VMD BGR scale', () => { - assert.match(template, /Isosurface 1.0 1 /) - assert.match(template, /mol color Volume 0/) - assert.match(template, /color scale method BGR/) - const mapped = apply_manifest_color_mapping(layers, entries, () => true) - assert.equal(mapped[0].color_volume_idx, 1) - assert.equal(mapped[0].isovalue, 0.1) // An explicit menu value overrides the template default. - assert.equal(mapped[0].show_negative, false) - assert.equal(mapped[1].visible, false) - assert.deepEqual(mapped[0].color_range, [-0.04, 0.02]) - const color = color_stop_interpolator(mapped[0].color_stops!) - assert.deepEqual(color(-1), [0, 0, 1]) - assert.deepEqual(color(0.333), [0, 0.5, 0.5]) - assert.deepEqual(color(0.666), [0, 1, 0]) - color(0.833).forEach((channel, idx) => assert.ok(Math.abs(channel - [0.5, 0.5, 0][idx]) < 1e-12)) - assert.deepEqual(color(2), [1, 0, 0]) - const reps = migrate_reps({}, { layers: mapped }, entries) - const surface = reps.items[1] - assert.deepEqual(surface.volume.colorScale?.stops, mapped[0].color_stops) - assert.equal(surface.volume.colorSourcePath, entries[1].path) - const restored = remap_rep_sources(JSON.parse(JSON.stringify(reps)), [...entries].reverse()) - assert.equal(restored.items[1].source.index, 1) - assert.equal(restored.items[1].volume.color_volume_idx, 0) -}) - -test('rejects missing, identical or incompatible coloring grids and invalid scales', () => { - assert.throws(() => apply_manifest_color_mapping(layers, entries.slice(0, 1), () => true), /separate coloring/) - assert.throws(() => apply_manifest_color_mapping(layers, entries, () => false), /same grid/) - const withMapping = (patch: object) => [{ ...entries[0], colorMapping: { ...entries[0].colorMapping!, ...patch } }, entries[1]] - assert.throws(() => apply_manifest_color_mapping(layers, withMapping({ path: entries[0].path }), () => true), /separate coloring/) - assert.throws(() => apply_manifest_color_mapping(layers, withMapping({ range: [1, -1] }), () => true), /increasing bounds/) - assert.throws(() => apply_manifest_color_mapping(layers, withMapping({ stops: [{ position: 0, color: 'bad' }] }), () => true)) - assert.deepEqual(apply_manifest_color_mapping(layers, [{ path: 'generic.cube' }], () => false), layers) +let server: Awaited> +let api: typeof import('../src/session-fields.ts') +test.before(async () => { + server = await createServer({ appType: 'custom', server: { middlewareMode: true, watch: null, hmr: false } }) + api = await server.ssrLoadModule('/src/session-fields.ts') }) +test.after(async () => { await server?.close() }) -test('the production manifest loader retains native geometry budgets on append and replacement', async () => { - const app = await readFile(new URL('../src/App.svelte', import.meta.url), 'utf8') - const start = app.indexOf(' const layer_for_entry =') - const end = app.indexOf(' const upsert_loaded_volume =', start) - assert.ok(start > 0 && end > start) - // Execute the real loading path with only network/volume decoding stubbed; - // losing this header used to silently resample initial high-quality grids. - const code = transpileModule(app.slice(start, end), { compilerOptions: { target: ScriptTarget.ES2022 } }).outputText - const responseHeaders = new Map([ - ['/api/volume/1', '2000000'], ['/api/volume/2', '1000000'], ['/api/volume/3', '3000000'], - ['/invalid', '-1'], ['/no-memory', '0'], - ]) - const loader = new Function('env', ` - const { fetch, read_geometry_memory_budget, apply_manifest_color_mapping } = env - let structure = {}, manifest = {}, volumeEntries = [], volumetricData = [], isosurfaceSettings = {}, activeVolumeIdx = 0 - const DEFAULT_ISOSURFACE_SETTINGS = {}, ESP_COLORS = {}, display_range = () => undefined - const resolve_volume_entry_url = (entry, base) => new URL(entry.path, base) - const read_matterviz_volume_response = async () => ({}), decode_matterviz_volume = x => x, adapt_matterviz_volume = x => x - const grids_compatible = () => true - ${code} - return { apply_entries, replace_volume_entry, settings: () => isosurfaceSettings } - `)({ - read_geometry_memory_budget, apply_manifest_color_mapping, - fetch: async (url: URL) => { - const headers = new Headers({ 'content-type': 'application/vnd.multiwfn.volume' }) - const budget = responseHeaders.get(url.pathname) - if (budget !== undefined) headers.set('x-matterviz-geometry-memory-budget', budget) - return { ok: true, headers } - }, - }) - const base = new URL('http://localhost/session/') - await loader.apply_entries(entries.map(entry => ({ ...entry, format: 'mwfn-volume-v2' })), base) - assert.equal(loader.settings().geometry_memory_budget_bytes, 1000000) - assert.equal(loader.settings().layers[0].color_volume_idx, 1) - loader.settings().layers[0].color_range = [-0.1, 0.1] - await loader.apply_entries([{ path: '/api/volume/3', format: 'mwfn-volume-v2' }], base, 'append') - assert.equal(loader.settings().geometry_memory_budget_bytes, 1000000) - assert.deepEqual(loader.settings().layers[0].color_range, [-0.1, 0.1]) - await assert.rejects(loader.apply_entries([{ path: '/invalid', format: 'mwfn-volume-v2' }], base), /invalid geometry memory budget/) - assert.equal(loader.settings().geometry_memory_budget_bytes, 1000000) - await loader.apply_entries([{ path: '/legacy', format: 'mwfn-volume-v1' }], base) - assert.equal(loader.settings().geometry_memory_budget_bytes, undefined) - - // Recomputing an existing orbital via a JSON response uses replacement, - // which must receive the newly admitted budget just like an appended grid. - await loader.replace_volume_entry(0, { path: '/api/volume/1', format: 'mwfn-volume-v2' }, base) - assert.equal(loader.settings().geometry_memory_budget_bytes, 2000000) - await loader.replace_volume_entry(0, { path: '/no-memory', format: 'mwfn-volume-v2' }, base) - assert.equal(loader.settings().geometry_memory_budget_bytes, 0) - await loader.replace_volume_entry(0, { path: '/legacy', format: 'mwfn-volume-v1' }, base) - assert.equal(loader.settings().geometry_memory_budget_bytes, 0) - await loader.replace_volume_entry(0, { path: '/api/volume/2', format: 'mwfn-volume-v2' }, base) - assert.equal(loader.settings().geometry_memory_budget_bytes, 1000000) - await loader.replace_volume_entry(0, { path: '/legacy', format: 'mwfn-volume-v1' }, base) - assert.equal(loader.settings().geometry_memory_budget_bytes, 1000000) - await assert.rejects(loader.replace_volume_entry(0, { path: '/invalid', format: 'mwfn-volume-v2' }, base), /invalid geometry memory budget/) - assert.equal(loader.settings().geometry_memory_budget_bytes, 1000000) +test('mapped layers retain stable source IDs, physical range and color order when fields move', () => { + const text = ['Cube','Finite', '1 -1 2 0', '-2 1 0 0', '-2 0 1 0', '-2 0 0 1', '1 0 0 2 0', '0 1 2 3 4 5 6 7'].join('\n') + const { structure, volumes: [base] } = api.parse_session_cube(text, false) + assert.deepEqual(base.origin, [-1, 2, 0]) + assert.deepEqual(structure.sites[0].xyz, [0, 2, 0]) + const source = { entry: { path: 'surface.cube', colorMapping: { path: 'color.cube', range: [-1, 1] as [number, number], stops: [ + { position: 0, color: '#ff0000' }, { position: .5, color: '#ffffff' }, { position: 1, color: '#0000ff' }] } }, volume: { ...base, id: 'density' } } + const color = { entry: { path: 'color.cube' }, volume: { ...base, id: 'potential' } } + const layer = api.layer_for_field(source, [color, source]) + assert.equal(layer.volume_id, 'density') + assert.equal(layer.color_volume_id, 'potential') + assert.deepEqual(layer, api.layer_for_field(source, [source, color])) + assert.deepEqual(layer.color_scale?.value_range, [-1, 1]) + assert.ok(typeof layer.color_scale?.scheme === 'string') + assert.throws(() => api.layer_for_field(source, [source]), /separate coloring dataset/) + assert.throws(() => api.layer_for_field(source, [source, { ...color, volume: { ...color.volume, origin: [1,0,0] } }]), /same grid/) + assert.notEqual(api.field_id({path: '/api/orbital', orbitalIndex: 1}), api.field_id({path: '/api/orbital', orbitalIndex: 2})) + assert.notEqual(api.field_id({path: 'multi.cube'}, 0), api.field_id({path: 'multi.cube'}, 1)) }) diff --git a/frontend/matterviz-viewer/tests/volume.test.ts b/frontend/matterviz-viewer/tests/volume.test.ts index 0109ca76..8883ac58 100644 --- a/frontend/matterviz-viewer/tests/volume.test.ts +++ b/frontend/matterviz-viewer/tests/volume.test.ts @@ -77,15 +77,11 @@ test('decodes the shared orbital golden frame and adapts geometry', async () => ...decoded, periodic_axes: [true, true, true], }) - const bohr = 0.529177249 - assert.deepEqual(adapted.grid, { - data: decoded.samples, - dimensions: [2, 2, 3], - order: 'x-fastest', - }) + const bohr = 0.529177210544 + assert.deepEqual(adapted.dims, [2, 2, 3]) + assert.deepEqual([...adapted.values], [1, 5, 9, 3, 7, 11, 2, 6, 10, 4, 8, 12]) + assert.equal(adapted.order, 'z_fastest') assert.deepEqual(adapted.origin, [bohr, 2 * bohr, 3 * bohr]) - assert.equal(adapted.origin_mode, 'absolute') - assert.equal(adapted.data_order, 'x_fastest') assert.equal(adapted.periodic, true) assert.deepEqual(adapted.lattice, [ [0.1 * (2 * bohr), 0, 0], @@ -104,12 +100,10 @@ test('preserves k-fastest Cube order in the flat scalar grid', async () => { ...decode_matterviz_volume(frame), periodic_axes: [false, false, false], }) - assert.deepEqual(adapted.grid, { - data: decode_matterviz_volume(frame).samples, - dimensions: [2, 2, 3], - order: 'z-fastest', - }) - assert.equal(adapted.data_order, 'z_fastest') + assert.deepEqual(adapted.dims, [2, 2, 3]) + assert.equal(adapted.values.buffer, frame.buffer) + assert.deepEqual(adapted.values, decode_matterviz_volume(frame).samples) + assert.equal(adapted.order, 'z_fastest') }) test('decodes signed samples and every quantity-unit pair', async () => { diff --git a/frontend/matterviz-viewer/tests/workbench-integration.test.ts b/frontend/matterviz-viewer/tests/workbench-integration.test.ts deleted file mode 100644 index a0725ab9..00000000 --- a/frontend/matterviz-viewer/tests/workbench-integration.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -import assert from 'node:assert/strict' -import test from 'node:test' -import type { IsosurfaceLayer, IsosurfaceSettings } from 'matterviz' -import { ESP_COLORMAP, surface_colormap } from '../src/esp.ts' -import { normalize_lighting } from '../src/lighting.ts' -import { normalize_surface_appearance, SURFACE_DEFAULTS } from '../src/material.ts' -import { create_workbench_state, parse_workbench_state, restore_workbench_state } from '../src/state.ts' - -test('one workbench snapshot preserves topology, material, lighting, camera and cross-volume coloring together', () => { - const entries = [ - { path: '/api/volume/11', analysisKind: 'esp-density', format: 'mwfn-volume-v1' }, - { path: '/api/volume/12', analysisKind: 'esp-potential', format: 'mwfn-volume-v1' }, - { path: '/api/volume/15', role: 'orbital', orbitalIndex: 42, format: 'mwfn-volume-v1' }, - ] - const layer = (volume_idx: number): IsosurfaceLayer => ({ - volume_idx, isovalue: 0.02, opacity: 0.8, visible: true, - color: '#2563eb', negative_color: '#dc2626', show_negative: true, - }) - // Layer ordering is independent of volume indices, as it can be after restoring - // or editing the workbench. ESP coloring must retain its potential-volume link. - const settings: IsosurfaceSettings = { - ...SURFACE_DEFAULTS, - isovalue: 0.02, opacity: 0.8, positive_color: '#2563eb', negative_color: '#dc2626', show_negative: true, - material: 'pbr', roughness: 0.46, metalness: 0.08, outline: 0.2, outlineWidth: 0.45, transmode: 1, - display_range: [[-0.5, 1.5], [0, 1], [0, 1]], - layers: [ - { ...layer(2), isovalue: 0.045, opacity: 0.72 }, - { ...layer(0), isovalue: 0.001, opacity: 0.6, color_volume_idx: 1, - colormap: surface_colormap(entries[1], 'interpolateViridis'), color_range: [-0.05, 0.2], show_negative: false }, - { ...layer(1), visible: false }, - ], - } - const camera = { - position: [4, -3, 2] as [number, number, number], target: [0.1, 0.2, 0.3] as [number, number, number], - up: [0.2, 0.9, -0.3] as [number, number, number], zoom: 1.7, projection: 'orthographic' as const, - } - const topologyDisplay = { - cpTypes: [false, true, true, false, true], pathTypes: [false, true, false, true], - labels: true, radius: 0.14, width: 3.5, - } - const source = { - manifest: { periodic: { enabled: true } }, sourceManifest: 'http://127.0.0.1/session/manifest.json', - entries, isosurfaceSettings: settings, activeVolume: 2, - atomSupercell: '2x1x1', showBoundaryAtoms: false, showUnitCell: true, - sceneProps: { ambient_light: 0, directional_light: 2.35 }, camera, topologyDisplay, - espLegend: { visible: true, position: { left: 24, top: 36 } }, - } - const snapshot = create_workbench_state(source) - const parsed = parse_workbench_state(JSON.parse(JSON.stringify(snapshot))) - const current: IsosurfaceSettings = { - ...settings, ...SURFACE_DEFAULTS, - layers: [layer(1), layer(2), layer(0)], - } - const currentBefore = structuredClone(current) - const restored = restore_workbench_state(parsed, { entries, isosurfaceSettings: current }) - const restoredLayers = new Map(restored.isosurfaceSettings.layers?.map((item) => [item.volume_idx, item])) - assert.deepEqual(restored.topologyDisplay, topologyDisplay) - assert.deepEqual(normalize_surface_appearance(restored.isosurfaceSettings), normalize_surface_appearance(settings)) - assert.deepEqual(normalize_lighting(restored.structureAppearance), source.sceneProps) - assert.deepEqual(restored.camera, camera) - assert.equal(restored.activeVolume, 2) - for (const original of settings.layers!) assert.deepEqual(restoredLayers.get(original.volume_idx), original) - assert.equal(restoredLayers.get(0)?.color_volume_idx, 1) - assert.equal(restoredLayers.get(0)?.colormap, ESP_COLORMAP) - assert.deepEqual(parsed.volumes.map((volume) => volume.path), entries.map((entry) => entry.path)) - assert.deepEqual(current, currentBefore, 'restore must not mutate the currently displayed layers') - - // Saving the combined restoration again must produce the same portable state, - // despite the different layer ordering and the changed current renderer defaults. - const resaved = create_workbench_state({ - ...source, isosurfaceSettings: restored.isosurfaceSettings, activeVolume: restored.activeVolume, - sceneProps: normalize_lighting(restored.structureAppearance), camera: restored.camera, - topologyDisplay: restored.topologyDisplay, espLegend: restored.espLegend, - }) - assert.deepEqual(JSON.parse(JSON.stringify(resaved)), JSON.parse(JSON.stringify(snapshot))) -}) diff --git a/frontend/matterviz-viewer/tests/workbench-layout.test.ts b/frontend/matterviz-viewer/tests/workbench-layout.test.ts index ed283191..23fce2d1 100644 --- a/frontend/matterviz-viewer/tests/workbench-layout.test.ts +++ b/frontend/matterviz-viewer/tests/workbench-layout.test.ts @@ -1,32 +1,7 @@ import assert from 'node:assert/strict' import { readFile } from 'node:fs/promises' import test from 'node:test' -import { createServer } from 'vite' -test('measurement readouts retain ordered, signed and periodic geometry outside the canvas', async () => { - const server = await createServer({ appType: 'custom', server: { middlewareMode: true, hmr: false, watch: null } }) - try { - const { default: Readout } = await server.ssrLoadModule('/src/MeasurementReadout.svelte') - const { render } = await server.ssrLoadModule('svelte/server') - const structure = { sites: [[0, 1, 0], [0, 0, 0], [1, 0, 0], [1, 0, -1]].map((xyz) => ({ xyz, species: [{ element: 'C', occu: 1 }] })) } - const show = (sites: number[], mode: string, source = structure, bonds: unknown[] = []) => render(Readout, { - props: { structure: source, sites, mode, bonds, on_remove_bond() {}, on_clear_selection() {} }, - }).body - assert.match(show([0, 1], 'distance'), /1\.0000 Å/) - assert.match(show([0, 1, 2], 'angle'), /90\.0000 °/) - assert.match(show([0, 1, 2, 3], 'angle'), /-90\.0000 °/) - assert.match(show([0, 0, 0], 'angle'), /Undefined/) - assert.doesNotMatch(show([0, 1], 'edit-atoms'), /Geometry measurement/) - const periodic = { sites: [[0.5, 0, 0], [9.5, 0, 0]].map((xyz) => ({ xyz, species: [{ element: 'C', occu: 1 }] })), - lattice: { matrix: [[10, 0, 0], [0, 10, 0], [0, 0, 10]], pbc: [true, true, true] } } - const text = show([0, 1], 'distance', periodic) - assert.match(text, /1\.0000 Å/) - assert.match(text, /Direct: 9\.0000 Å/) - const results = show([], 'distance', structure, [{ key: '1:2:mayer', atoms: 'C1 - C2', method: 'Mayer', value: 1.234567 }]) - assert.match(results, /1\.234567/) - assert.match(results, /C1 - C2/) - } finally { await server.close() } -}) test('backend work does not unmount Structure and all numerical readouts have a separate layout row', async () => { const app = await readFile(new URL('../src/App.svelte', import.meta.url), 'utf8') @@ -35,9 +10,7 @@ test('backend work does not unmount Structure and all numerical readouts have a assert.doesNotMatch(app, /bind:loading\s/) assert.doesNotMatch(app, /Working\.\.\./) assert.match(app, /
/) - assert.match(app, /<\/div>\s*\{#if loading \|\| measurementSites.length \|\| bondResults.length\}/) assert.match(css, /\.viewer-shell\s*\{[^}]*grid-template-rows: minmax\(0, 1fr\) auto/) - assert.match(css, /\.scene-viewport \.measure-label\s*\{[^}]*display: none/) }) test('frontier shortcuts use declared HOMO metadata and scroll only the orbital list', async () => { diff --git a/frontend/matterviz-viewer/tests/workbench-plots.test.ts b/frontend/matterviz-viewer/tests/workbench-plots.test.ts index 03c72b53..b63daa86 100644 --- a/frontend/matterviz-viewer/tests/workbench-plots.test.ts +++ b/frontend/matterviz-viewer/tests/workbench-plots.test.ts @@ -87,7 +87,7 @@ test('result navigation keeps renderers mounted and preserves original calculati assert.match(app, /class:inactive=\{activeResult !== 'scene'\}/) assert.match(app, /class:inactive=\{activeResult !== plot.id\}/) assert.match(app, /onExported=\{return_to_multiwfn\}/) - assert.match(app, /scene_registry.get\(canvas\)/) + assert.match(app, /scene_to_png_blob\(canvas,/) assert.doesNotMatch(app, /\{#if plotArtifact\}/) }) diff --git a/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r23.tgz b/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r23.tgz deleted file mode 100644 index c096dcff..00000000 Binary files a/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r23.tgz and /dev/null differ diff --git a/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r24.tgz b/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r24.tgz deleted file mode 100644 index 4275312d..00000000 Binary files a/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r24.tgz and /dev/null differ diff --git a/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.freq1.tgz b/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.freq1.tgz deleted file mode 100644 index 977aeb1c..00000000 Binary files a/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.freq1.tgz and /dev/null differ diff --git a/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.material1.tgz b/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.material1.tgz deleted file mode 100644 index f2e238ab..00000000 Binary files a/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.material1.tgz and /dev/null differ diff --git a/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.material2.tgz b/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.material2.tgz deleted file mode 100644 index f34ccd35..00000000 Binary files a/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.material2.tgz and /dev/null differ diff --git a/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.reps1.tgz b/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.reps1.tgz deleted file mode 100644 index 4ada5a00..00000000 Binary files a/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.reps1.tgz and /dev/null differ diff --git a/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.reps2.tgz b/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.reps2.tgz deleted file mode 100644 index 1fec7d8e..00000000 Binary files a/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.reps2.tgz and /dev/null differ diff --git a/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.surface1.picking1.tgz b/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.surface1.picking1.tgz deleted file mode 100644 index ba767fda..00000000 Binary files a/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.surface1.picking1.tgz and /dev/null differ diff --git a/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.surface1.tgz b/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.surface1.tgz deleted file mode 100644 index 3b8cb154..00000000 Binary files a/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.surface1.tgz and /dev/null differ diff --git a/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.tgz b/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.tgz deleted file mode 100644 index 4ebb4382..00000000 Binary files a/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.tgz and /dev/null differ diff --git a/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.topology1.tgz b/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.topology1.tgz deleted file mode 100644 index e67e4017..00000000 Binary files a/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.topology1.tgz and /dev/null differ diff --git a/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.topology2.tgz b/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.topology2.tgz deleted file mode 100644 index 121e8338..00000000 Binary files a/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.topology2.tgz and /dev/null differ diff --git a/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.upstream1.tgz b/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.upstream1.tgz deleted file mode 100644 index 3dc5bda4..00000000 Binary files a/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.upstream1.tgz and /dev/null differ diff --git a/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.workbench1.tgz b/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.workbench1.tgz deleted file mode 100644 index 51a36cf3..00000000 Binary files a/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.workbench1.tgz and /dev/null differ diff --git a/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.workbench2.tgz b/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.workbench2.tgz deleted file mode 100644 index 7c355ba2..00000000 Binary files a/frontend/matterviz-viewer/vendor/matterviz-0.4.2-multiwfn.d8719d12.r25.workbench2.tgz and /dev/null differ diff --git a/frontend/matterviz-viewer/vendor/patches/matterviz-0.4.2-multiwfn.d8719d12.r25.freq1.patch b/frontend/matterviz-viewer/vendor/patches/matterviz-0.4.2-multiwfn.d8719d12.r25.freq1.patch deleted file mode 100644 index 81486499..00000000 --- a/frontend/matterviz-viewer/vendor/patches/matterviz-0.4.2-multiwfn.d8719d12.r25.freq1.patch +++ /dev/null @@ -1,113 +0,0 @@ ---- a/dist/structure/Structure.svelte -+++ b/dist/structure/Structure.svelte -@@ -118,6 +118,7 @@ - - let { - structure = $bindable(), -+ structure_series_key = undefined, - bonds = $bindable(), - added_bonds = $bindable([]), - removed_bonds = $bindable([]), -@@ -215,6 +216,8 @@ - ...rest - }: { - structure?: AnyStructure -+ // Stable identity for coordinate-only frames; change it when topology changes. -+ structure_series_key?: unknown - added_bonds?: StructureBond[] - removed_bonds?: StructureBond[] - bond_order_overrides?: StructureBond[] -@@ -1007,7 +1010,8 @@ - // change site indices (skip first run to preserve parent-provided selections) - let first_run = true - $effect(() => { -- void [supercell_scaling, show_image_atoms, structure, cell_type] // track reactively -+ // Coordinate-only frames share their camera and selection (upstream series-key contract). -+ void [supercell_scaling, show_image_atoms, structure_series_key ?? structure, cell_type] - if (first_run) { - first_run = false - return -@@ -1076,6 +1080,7 @@ - // selection bindings, and per-pane chrome differ and stay on each snippet below. - let shared_viewport_props = $derived({ - structure: internal_displayed_structure, -+ series_key: structure_series_key, - base_structure: cell_transformed_structure, - scene_props, - scene_children, -@@ -1125,7 +1130,8 @@ - $effect(() => { - // untrack: clearing must not add moved_panes as a dependency, else a pane move - // (which adds to moved_panes) would immediately re-run this and clear it again. -- if (structure) untrack(() => moved_panes.clear()) -+ const series = structure_series_key ?? structure -+ if (series !== undefined) untrack(() => moved_panes.clear()) - }) - - // Clear stale camera target and position so StructureScene uses the new ---- a/dist/structure/Structure.svelte.d.ts -+++ b/dist/structure/Structure.svelte.d.ts -@@ -17,6 +17,7 @@ - type EventHandler = (data: StructureHandlerData) => void; - type $$ComponentProps = { - structure?: AnyStructure; -+ structure_series_key?: unknown; - added_bonds?: StructureBond[]; - removed_bonds?: StructureBond[]; - bond_order_overrides?: StructureBond[]; ---- a/dist/structure/StructureViewport.svelte -+++ b/dist/structure/StructureViewport.svelte -@@ -80,6 +80,7 @@ - - // Shared scene inputs (one-way) - structure = undefined, -+ series_key = undefined, - base_structure = undefined, - scene_props = {}, - scene_children, -@@ -147,6 +148,7 @@ - on_camera_move?: (data: StructureHandlerData) => void - on_camera_reset?: (data: StructureHandlerData) => void - structure?: AnyStructure -+ series_key?: unknown - base_structure?: AnyStructure - scene_props?: ComponentProps - scene_children?: import('svelte').Snippet -@@ -226,7 +228,7 @@ - let initial_camera_target = $state(undefined) - // Periodic image generation passes a raw object. Preserve its identity so the - // camera snapshot effect does not compare a deep proxy against the raw input. -- let snapshot_structure = $state.raw(undefined) -+ let snapshot_structure = $state.raw(undefined) - let snapshot_structure_initialized = false - let camera_is_moving = $state(false) - let suppress_camera_change = false -@@ -282,7 +284,7 @@ - // outside StructureScene's keyed camera subtree so X/Y orbit followed by a declarative - // Z roll still resets to the original position, target, up, and zoom. - $effect(() => { -- const current_structure = structure -+ const current_structure = series_key ?? structure - // Establish these dependencies even on the structure-initialization pass below. - // Otherwise the early return prevents the effect from rerunning when the camera mounts. - const current_camera = camera ---- a/dist/structure/StructureViewport.svelte.d.ts -+++ b/dist/structure/StructureViewport.svelte.d.ts -@@ -24,6 +24,7 @@ - on_camera_move?: (data: StructureHandlerData) => void; - on_camera_reset?: (data: StructureHandlerData) => void; - structure?: AnyStructure; -+ series_key?: unknown; - base_structure?: AnyStructure; - scene_props?: ComponentProps; - gizmo?: boolean | ComponentProps[`gizmo`]; ---- a/package.json -+++ b/package.json -@@ -1,6 +1,6 @@ - { - "name": "matterviz", -- "version": "0.4.2-multiwfn.d8719d12.r25.reps2", -+ "version": "0.4.2-multiwfn.d8719d12.r25.freq1", - "description": "Interactive visualizations for materials science: periodic tables, 3D structures, MD trajectories, heatmaps, scatter plots.", - "keywords": [ - "chemistry", diff --git a/frontend/matterviz-viewer/vendor/patches/matterviz-0.4.2-multiwfn.d8719d12.r25.material1.patch b/frontend/matterviz-viewer/vendor/patches/matterviz-0.4.2-multiwfn.d8719d12.r25.material1.patch deleted file mode 100644 index 2d8acb80..00000000 --- a/frontend/matterviz-viewer/vendor/patches/matterviz-0.4.2-multiwfn.d8719d12.r25.material1.patch +++ /dev/null @@ -1,405 +0,0 @@ -diff -ruN a/dist/colors/index.d.ts b/dist/colors/index.d.ts ---- a/dist/colors/index.d.ts 1985-10-26 16:15:00.000000000 +0800 -+++ b/dist/colors/index.d.ts 2026-09-11 21:39:50.107189044 +0800 -@@ -1,7 +1,10 @@ - import * as d3_sc from 'd3-scale-chromatic'; --export type D3InterpolateName = keyof typeof d3_sc & `interpolate${string}`; -+export type D3InterpolateName = (keyof typeof d3_sc & `interpolate${string}`) | `interpolateTransFlag`; - export type D3ColorSchemeName = D3InterpolateName extends `interpolate${infer Name}` ? Name : never; - export declare const get_d3_interpolator: (name: D3InterpolateName) => ((t: number) => string); -+export declare const interpolateTransFlag: (t: number) => string; -+export declare const trans_flag_coordinate: (value: number, range: [number, number]) => number; -+export declare const trans_flag_color: (value: number, range: [number, number]) => string; - export declare const COLOR_SCALE_TYPES: readonly ["continuous", "categorical"]; - export type ColorScaleType = (typeof COLOR_SCALE_TYPES)[number]; - export declare const DEFAULT_CATEGORY_COLORS: Record; -diff -ruN a/dist/colors/index.js b/dist/colors/index.js ---- a/dist/colors/index.js 1985-10-26 16:15:00.000000000 +0800 -+++ b/dist/colors/index.js 2026-09-11 21:59:18.451787501 +0800 -@@ -8,7 +8,27 @@ - import muted_colors from './muted-colors.json' with { type: 'json' }; - import pastel_colors from './pastel-colors.json' with { type: 'json' }; - import vesta_colors from './vesta-colors.json' with { type: 'json' }; -+export const interpolateTransFlag = (t) => { -+ const value = clamp01(t); -+ const start = value <= 0.5 ? [245, 169, 184] : [255, 255, 255]; -+ const end = value <= 0.5 ? [255, 255, 255] : [91, 206, 250]; -+ const fraction = value <= 0.5 ? value * 2 : (value - 0.5) * 2; -+ return rgb(...start.map((channel, idx) => channel + (end[idx] - channel) * fraction)).formatHex(); -+}; -+// A signed scientific palette anchors white at physical zero, including -+// asymmetric or one-sided ranges. Sorting handles reversed display domains. -+export const trans_flag_coordinate = (value, range) => { -+ const [first, second] = range; -+ if (![value, first, second].every(Number.isFinite) || first === second) return 0.5; -+ const lower = Math.min(0, first, second); -+ const upper = Math.max(0, first, second); -+ if (value < 0) return lower < 0 ? 0.5 * (1 - clamp01(value / lower)) : 0.5; -+ return upper > 0 ? 0.5 + 0.5 * clamp01(value / upper) : 0.5; -+}; -+export const trans_flag_color = (value, range) => interpolateTransFlag(trans_flag_coordinate(value, range)); - export const get_d3_interpolator = (name) => { -+ if (name === `interpolateTransFlag`) -+ return interpolateTransFlag; - const candidate = d3_sc[name]; - return typeof candidate === `function` ? candidate : d3_sc.interpolateViridis; - }; -diff -ruN a/dist/isosurface/Isosurface.svelte b/dist/isosurface/Isosurface.svelte ---- a/dist/isosurface/Isosurface.svelte 1985-10-26 16:15:00.000000000 +0800 -+++ b/dist/isosurface/Isosurface.svelte 2026-09-11 21:36:46.268010972 +0800 -@@ -36,6 +36,7 @@ - import type { IsosurfaceLayer, IsosurfaceSettings, VolumetricData } from './types' - import type { ScalarGridLike } from './scalar-grid' - import { is_scalar_grid } from './scalar-grid' -+ import { install_isosurface_shading } from './material' - import { - dispose_unretained_geometries, - release_isosurface_geometry, -@@ -718,7 +719,7 @@ - equal to the UI value instead of making atoms inside appear nearly black. --> - {@const pass_opacity = transparent ? 1 - Math.sqrt(1 - opacity) : opacity} - -- {#key `${vertex_colored}-${settings.material}-${settings.flat_shading}`} -+ {#key `${vertex_colored}-${settings.material}-${settings.flat_shading}-${settings.outline}-${settings.outlineWidth}-${settings.transmode}`} - {#if settings.wireframe} - - - {:else if settings.material === `glossy`} - install_isosurface_shading(material, settings)} - {color} - vertexColors={vertex_colored} - {transparent} -@@ -761,6 +763,7 @@ - /> - {:else if settings.material === `pbr`} - install_isosurface_shading(material, settings)} - {color} - vertexColors={vertex_colored} - {transparent} -@@ -773,6 +776,7 @@ - /> - {:else} - install_isosurface_shading(material, settings)} - {color} - vertexColors={vertex_colored} - {transparent} -diff -ruN a/dist/isosurface/coloring.d.ts b/dist/isosurface/coloring.d.ts ---- a/dist/isosurface/coloring.d.ts 1985-10-26 16:15:00.000000000 +0800 -+++ b/dist/isosurface/coloring.d.ts 2026-09-11 21:36:46.268010972 +0800 -@@ -1,7 +1,7 @@ - import type { D3InterpolateName } from '../colors'; - import type { Vec2 } from '../math'; - import type { DataRange } from './types'; --export declare const ISO_COLORMAPS: readonly ["interpolateViridis", "interpolatePlasma", "interpolateInferno", "interpolateMagma", "interpolateCividis", "interpolateTurbo", "interpolateRdBu", "interpolateRdYlBu", "interpolateSpectral", "interpolatePiYG", "interpolateBrBG", "interpolatePuOr"]; -+export declare const ISO_COLORMAPS: readonly ["interpolateTransFlag", "interpolateViridis", "interpolatePlasma", "interpolateInferno", "interpolateMagma", "interpolateCividis", "interpolateTurbo", "interpolateRdBu", "interpolateRdYlBu", "interpolateSpectral", "interpolatePiYG", "interpolateBrBG", "interpolatePuOr"]; - export type IsoColormap = (typeof ISO_COLORMAPS)[number]; - export declare const DEFAULT_ISO_COLORMAP: IsoColormap; - export declare const is_signed_range: (data_range: DataRange) => boolean; -diff -ruN a/dist/isosurface/coloring.js b/dist/isosurface/coloring.js ---- a/dist/isosurface/coloring.js 1985-10-26 16:15:00.000000000 +0800 -+++ b/dist/isosurface/coloring.js 2026-09-11 21:39:50.107189044 +0800 -@@ -1,8 +1,9 @@ --import { get_d3_interpolator } from '../colors'; -+import { get_d3_interpolator, trans_flag_coordinate } from '../colors'; - import { Color } from 'three'; - // Curated continuous colormaps offered in the isosurface controls UI. - // Sequential maps for densities/potential magnitudes, diverging for signed fields. - export const ISO_COLORMAPS = [ -+ `interpolateTransFlag`, - `interpolateViridis`, - `interpolatePlasma`, - `interpolateInferno`, -@@ -37,9 +38,11 @@ - if (cached) - return cached; - const interpolator = get_d3_interpolator(colormap); -- const lut = new Float32Array(LUT_SIZE * 3); -- for (let idx = 0; idx < LUT_SIZE; idx++) { -- const [red, green, blue] = parse_linear_rgb(interpolator(idx / (LUT_SIZE - 1))); -+ // An odd table size preserves exact white at zero for the Trans Flag map. -+ const size = colormap === `interpolateTransFlag` ? 257 : LUT_SIZE; -+ const lut = new Float32Array(size * 3); -+ for (let idx = 0; idx < size; idx++) { -+ const [red, green, blue] = parse_linear_rgb(interpolator(idx / (size - 1))); - lut[idx * 3] = red; - lut[idx * 3 + 1] = green; - lut[idx * 3 + 2] = blue; -@@ -68,9 +71,11 @@ - continue; - } - // span === 0 maps everything to the middle of the colormap -- const normalized = span === 0 ? 0.5 : (value - range_min) * inv_span; -+ const normalized = colormap === `interpolateTransFlag` -+ ? trans_flag_coordinate(value, color_range) -+ : span === 0 ? 0.5 : (value - range_min) * inv_span; - const clamped = normalized < 0 ? 0 : Math.min(1, normalized); -- const lut_idx = Math.round(clamped * (LUT_SIZE - 1)) * 3; -+ const lut_idx = Math.round(clamped * (lut.length / 3 - 1)) * 3; - colors[idx * 3] = lut[lut_idx]; - colors[idx * 3 + 1] = lut[lut_idx + 1]; - colors[idx * 3 + 2] = lut[lut_idx + 2]; -diff -ruN a/dist/isosurface/marching-cubes-worker.js b/dist/isosurface/marching-cubes-worker.js ---- a/dist/isosurface/marching-cubes-worker.js 1985-10-26 16:15:00.000000000 +0800 -+++ b/dist/isosurface/marching-cubes-worker.js 2026-09-11 21:36:46.268010972 +0800 -@@ -1,6 +1,7 @@ - import { marching_cubes_typed, preflight_marching_cubes } from '../marching-cubes'; - - const ctx = globalThis; -+const is_shared_buffer = (buffer) => typeof SharedArrayBuffer !== `undefined` && buffer instanceof SharedArrayBuffer; - - ctx.onmessage = (event) => { - const message = event.data; -@@ -18,7 +19,7 @@ - } - const result = marching_cubes_typed(grid, iso_value, lattice, options); - const transfer = [result.positions.buffer, result.normals.buffer, result.indices.buffer]; -- if (!(return_buffer instanceof SharedArrayBuffer)) transfer.push(return_buffer); -+ if (!is_shared_buffer(return_buffer)) transfer.push(return_buffer); - ctx.postMessage({ - job_id, - ok: true, -@@ -31,7 +32,7 @@ - } catch (error) { - const message_text = error instanceof Error ? error.message : String(error); - const transfer = []; -- if (return_buffer && !(return_buffer instanceof SharedArrayBuffer)) transfer.push(return_buffer); -+ if (return_buffer && !is_shared_buffer(return_buffer)) transfer.push(return_buffer); - ctx.postMessage({ - job_id, - ok: false, -diff -ruN a/dist/isosurface/material.d.ts b/dist/isosurface/material.d.ts ---- a/dist/isosurface/material.d.ts 1970-01-01 08:00:00.000000000 +0800 -+++ b/dist/isosurface/material.d.ts 2026-09-11 21:36:46.496196848 +0800 -@@ -0,0 +1,3 @@ -+import type { Material } from 'three'; -+import type { IsosurfaceSettings } from './types'; -+export declare function install_isosurface_shading(material: Material, settings: IsosurfaceSettings): void; -diff -ruN a/dist/isosurface/material.js b/dist/isosurface/material.js ---- a/dist/isosurface/material.js 1970-01-01 08:00:00.000000000 +0800 -+++ b/dist/isosurface/material.js 2026-09-11 21:36:46.386038148 +0800 -@@ -0,0 +1,39 @@ -+const OUTPUT_CHUNK = `#include `; -+const UNIFORMS = ` -+uniform float mvOutline; -+uniform float mvOutlineWidth; -+uniform float mvTransmode; -+`; -+const SHADING = ` -+// Three's geometryViewDir includes the orthographic-camera correction. -+float mvFacing = clamp(dot(normal, geometryViewDir), 0.0, 1.0); -+float mvRim = pow(max(0.0, 1.0 - mvFacing * mvFacing), max(0.001, (1.0 - mvOutlineWidth) * 32.0)); -+gl_FragColor.rgb *= 1.0 - mvOutline * mvRim; -+if (mvTransmode > 0.5 && gl_FragColor.a > 0.0 && gl_FragColor.a < 1.0) { -+ float mvAlpha = 1.0 + cos(3.14159265 * (1.0 - gl_FragColor.a) * mvFacing); -+ gl_FragColor.a = mvAlpha * mvAlpha * 0.25; -+} -+`; -+const bounded = (value, fallback) => Number.isFinite(value) -+ ? Math.min(1, Math.max(0, value)) -+ : fallback; -+ -+// onBeforeCompile sees unexpanded ShaderLib includes, not ShaderChunk output. -+// Keep the standard output chunk for opaque/transmission handling, then shade -+// in linear space before tone mapping, output color conversion and fog. -+export function install_isosurface_shading(material, settings) { -+ material.onBeforeCompile = (shader) => { -+ if (!shader.fragmentShader.includes(OUTPUT_CHUNK)) { -+ throw new Error(`Unsupported Three shader: missing isosurface output chunk`); -+ } -+ shader.uniforms.mvOutline = { value: bounded(settings.outline, 0) }; -+ shader.uniforms.mvOutlineWidth = { value: bounded(settings.outlineWidth, 0.6) }; -+ shader.uniforms.mvTransmode = { value: settings.transmode === 1 ? 1 : 0 }; -+ shader.fragmentShader = UNIFORMS + shader.fragmentShader.replace( -+ OUTPUT_CHUNK, -+ OUTPUT_CHUNK + SHADING, -+ ); -+ }; -+ material.customProgramCacheKey = () => `multiwfn-isosurface-material-v1`; -+ material.needsUpdate = true; -+} -diff -ruN a/dist/isosurface/types.d.ts b/dist/isosurface/types.d.ts ---- a/dist/isosurface/types.d.ts 1985-10-26 16:15:00.000000000 +0800 -+++ b/dist/isosurface/types.d.ts 2026-09-11 21:36:46.268010972 +0800 -@@ -52,6 +52,9 @@ - shininess?: number; - specular?: number; - flat_shading?: boolean; -+ outline?: number; -+ outlineWidth?: number; -+ transmode?: number; - halo: number; - layers?: IsosurfaceLayer[]; - display_range?: [Vec2, Vec2, Vec2]; -diff -ruN a/dist/isosurface/types.js b/dist/isosurface/types.js ---- a/dist/isosurface/types.js 1985-10-26 16:15:00.000000000 +0800 -+++ b/dist/isosurface/types.js 2026-09-11 21:36:46.268010972 +0800 -@@ -147,6 +147,9 @@ - shininess: 18, - specular: 0.12, - flat_shading: false, -+ outline: 0, -+ outlineWidth: 0.6, -+ transmode: 0, - halo: 0, - }; - // Compute reasonable isosurface settings from a volume's data range. -diff -ruN a/dist/plot/core/components/ColorBar.svelte b/dist/plot/core/components/ColorBar.svelte ---- a/dist/plot/core/components/ColorBar.svelte 1985-10-26 16:15:00.000000000 +0800 -+++ b/dist/plot/core/components/ColorBar.svelte 2026-09-11 21:39:50.107189044 +0800 -@@ -1,5 +1,5 @@ -