Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
507e8e32d2 | ||
|
|
491b3f6212 | ||
|
|
111a6f1a94 | ||
|
|
43e2144090 | ||
|
|
8e45f2c275 | ||
|
|
86ba1bda5c | ||
|
|
93b2ae343c | ||
|
|
7dd50a3ca4 | ||
|
|
2e28a69c04 | ||
|
|
69c1440cbe | ||
|
|
12487794a3 | ||
|
|
8fe31545ea | ||
|
|
4c18322a34 | ||
|
|
02172f9a7e | ||
|
|
a0b4a69452 | ||
|
|
c83b803f63 | ||
|
|
db80b75814 | ||
|
|
31bc886c7a | ||
|
|
ed9ec7748d | ||
|
|
79d583ea0f | ||
|
|
162bb421f1 | ||
|
|
54f50f9518 | ||
|
|
a0d11f1c22 | ||
|
|
dddb2d0584 | ||
|
|
b19277ae7a | ||
|
|
e06c85eb9e | ||
|
|
cb7e3a2711 | ||
|
|
080ff048c6 | ||
|
|
3d51bde9dd | ||
|
|
d3ed8ffb05 | ||
|
|
072139353f | ||
|
|
08f669acad | ||
|
|
d7ec7f486a | ||
|
|
d9824de4a5 | ||
|
|
fbaba5fecd | ||
|
|
0bf150633c | ||
|
|
c1fd58c6ce | ||
|
|
90948833e0 | ||
|
|
73987bdbae | ||
|
|
7df37d4b15 | ||
|
|
52c12e2ad7 | ||
|
|
1fcc7acf84 | ||
|
|
3aab588b8b | ||
|
|
f074e10442 | ||
|
|
05abcec6c2 | ||
|
|
012119e2c2 | ||
|
|
f5a84f5f74 | ||
|
|
910d437819 | ||
|
|
0e4ea5e099 | ||
|
|
ed2541170a | ||
|
|
0bbdd463ea | ||
|
|
65fb1112ab | ||
|
|
de8b7b6321 | ||
|
|
70c5c9b26f | ||
|
|
f4b6d1dbff | ||
|
|
2d5dfb2137 | ||
|
|
ad84a52ed2 | ||
|
|
5758dc7911 | ||
|
|
29af2aef91 | ||
|
|
696b64c30f | ||
|
|
a0f48c7207 | ||
|
|
9e38fe866d | ||
|
|
c26b142630 | ||
|
|
6bb3b04e60 | ||
|
|
b1180bf987 | ||
|
|
786121c21a | ||
|
|
e223a6256a | ||
|
|
fe557054ef | ||
|
|
fc85550534 | ||
|
|
3d8864c313 | ||
|
|
2443746b35 | ||
|
|
8b12cdd5c7 | ||
|
|
6b9e669c7e | ||
|
|
eb66b86e26 | ||
|
|
f78680e091 | ||
|
|
13b506150c | ||
|
|
bdd84a491d | ||
|
|
904dc3381b | ||
|
|
9dcbb9c9a6 | ||
|
|
8df4ea040c | ||
|
|
e8cada94d0 | ||
|
|
f8e0be970e | ||
|
|
94c98e0c0b | ||
|
|
ffb71de6e1 | ||
|
|
a11b971dae | ||
|
|
6bfa0b410a | ||
|
|
29e7a4ca31 | ||
|
|
794122a302 | ||
|
|
860707efa6 | ||
|
|
a84a8339ae | ||
|
|
f89545a66a | ||
|
|
0f99a1c687 | ||
|
|
9fc8e27933 | ||
|
|
b73a3bb976 | ||
|
|
7d689fb6a2 | ||
|
|
0b6b6c966c | ||
|
|
1fbb5581ea | ||
|
|
f6d227d8cb | ||
|
|
22f1006f71 | ||
|
|
1c16972cf2 | ||
|
|
b0d0fc9900 | ||
|
|
321add294b | ||
|
|
4c91f9b731 | ||
|
|
8409101483 | ||
|
|
e0d5adba23 | ||
|
|
06b98f01c7 | ||
|
|
2188d891ff | ||
|
|
1fc9d1e8d5 | ||
|
|
94a10a1bf3 | ||
|
|
14e2d25e68 | ||
|
|
4a60674530 | ||
|
|
ddde08fb4c | ||
|
|
a8f6be3bee | ||
|
|
872dfdb421 | ||
|
|
854ced2888 | ||
|
|
c8bd641e27 | ||
|
|
48cae3eb1d |
No files matched your search
@@ -41,6 +41,6 @@ body:
|
||||
id: version
|
||||
attributes:
|
||||
label: Version and platform
|
||||
placeholder: "v0.5.7 (or commit), macOS 15 arm64"
|
||||
placeholder: "v0.5.9 (or commit), macOS 15 arm64"
|
||||
validations:
|
||||
required: true
|
||||
@@ -21,6 +21,8 @@ modal problems with its own solver. AI agents can drive it over MCP (`fieldcraft
|
||||
To start with a sample model, run the app with `--sample cantilever` (macOS:
|
||||
`/Applications/FieldCraft.app/Contents/MacOS/FieldCraft --sample cantilever`).
|
||||
|
||||
**Updates.** {update_signing}
|
||||
|
||||
**Signing.** {macos_signing} The Linux and Windows builds are not signed; on Windows, SmartScreen
|
||||
may say "Windows protected your PC": choose **More info**, then **Run anyway**.
|
||||
|
||||
|
||||
@@ -53,6 +53,10 @@ jobs:
|
||||
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
|
||||
- name: Build the web app
|
||||
working-directory: apps/fieldcraft-web
|
||||
env:
|
||||
# Usage analytics only in the deployed build (main), and only with the user's consent
|
||||
# (docs/privacy.md); develop builds get an empty key, which sends nothing.
|
||||
FIELDCRAFT_POSTHOG_KEY: ${{ github.ref == 'refs/heads/main' && secrets.POSTHOG_KEY || '' }}
|
||||
run: trunk build --release --public-url /fieldcraft/
|
||||
- name: Bundle size
|
||||
run: |
|
||||
|
||||
@@ -3,13 +3,14 @@
|
||||
#
|
||||
# A push to `main` (fast-forwarded from a verified `develop` commit; main holds released code only)
|
||||
# builds every package and creates or updates the
|
||||
# DRAFT GitHub Release "FieldCraft v<version>", with SHA256SUMS.txt and generated notes. The
|
||||
# DRAFT GitHub Release "FieldCraft v<version>", with SHA256SUMS.txt (signed with the release key
|
||||
# into SHA256SUMS.txt.minisig when the FIELDCRAFT_SIGNING_KEY secret exists) and generated notes. The
|
||||
# version is [workspace.package] version in Cargo.toml; a suffix (0.2.0-rc.1) makes a
|
||||
# pre-release. A person verifies the draft and publishes it; this workflow never publishes,
|
||||
# and pushes to develop or tags never start it.
|
||||
#
|
||||
# macOS universal (arm64 + x86_64) .dmg with FieldCraft.app, the CLI as a .zip packaging/macos
|
||||
# Linux x86_64 (glibc 2.35+) .tar.gz and .AppImage packaging/linux
|
||||
# Linux x86_64 (glibc 2.35+) .tar.gz, .AppImage, .deb and .rpm packaging/linux
|
||||
# Windows x64 .zip with fieldcraft.exe and fieldcraft-cli.exe packaging/windows
|
||||
#
|
||||
# macOS: signed with a Developer ID and notarized when the APPLE_* secrets exist, ad-hoc
|
||||
@@ -97,6 +98,8 @@ jobs:
|
||||
- name: Build, sign, notarize and package (the dmg is mounted and checked)
|
||||
id: package
|
||||
env:
|
||||
# The analytics project key (docs/privacy.md), built in; never printed.
|
||||
FIELDCRAFT_POSTHOG_KEY: ${{ secrets.POSTHOG_KEY }}
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
@@ -119,33 +122,76 @@ jobs:
|
||||
timeout-minutes: 90
|
||||
env:
|
||||
FIELDCRAFT_VERSION: ${{ needs.version.outputs.version }}
|
||||
# The .deb and .rpm builders (both MIT), pinned.
|
||||
CARGO_DEB_VERSION: 3.8.0
|
||||
CARGO_GENERATE_RPM_VERSION: 0.21.0
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Install packaging tools
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends desktop-file-utils
|
||||
sudo apt-get install -y --no-install-recommends desktop-file-utils lintian rpm
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
|
||||
with:
|
||||
key: release-linux-x86_64
|
||||
# Release runs are rare: only release-branch runs keep a cache, so dry runs don't evict CI's.
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
- name: Build and package (tar.gz, AppImage)
|
||||
- name: Install cargo-deb and cargo-generate-rpm
|
||||
run: |
|
||||
cargo install --locked --version "$CARGO_DEB_VERSION" cargo-deb
|
||||
cargo install --locked --version "$CARGO_GENERATE_RPM_VERSION" cargo-generate-rpm
|
||||
- name: Build and package (tar.gz, AppImage, deb, rpm)
|
||||
env:
|
||||
# The analytics project key (docs/privacy.md), built in; never printed.
|
||||
FIELDCRAFT_POSTHOG_KEY: ${{ secrets.POSTHOG_KEY }}
|
||||
run: packaging/linux/package.sh
|
||||
- name: Check the packages
|
||||
run: |
|
||||
. packaging/env.sh
|
||||
list="$(tar -tzf dist/release/*.tar.gz)"
|
||||
base="fieldcraft-$VERSION-linux-x86_64"
|
||||
deb="dist/release/fieldcraft_${VERSION}_amd64.deb"
|
||||
rpm="dist/release/fieldcraft-$VERSION.x86_64.rpm"
|
||||
list="$(tar -tzf "dist/release/$base.tar.gz")"
|
||||
for f in bin/fieldcraft bin/fieldcraft-cli "share/applications/$APP_ID.desktop" \
|
||||
share/doc/fieldcraft/THIRD-PARTY-LICENSES.txt; do
|
||||
grep -Fx -- "fieldcraft-$VERSION-linux-x86_64/$f" <<<"$list"
|
||||
grep -Fx -- "$base/$f" <<<"$list"
|
||||
done
|
||||
# The .deb and .rpm carry the tar.gz's files under /usr (the .deb adds its copyright
|
||||
# file); their lists live in apps/fieldcraft/Cargo.toml, so a drift fails here.
|
||||
files() { grep -v '/$' | sed -E "s#^(\./|/|$base/)##; s#^usr/##" | grep -vx 'share/doc/fieldcraft/copyright' | sort; }
|
||||
diff <(files <<<"$list") <(dpkg-deb --fsys-tarfile "$deb" | tar -t | files)
|
||||
diff <(files <<<"$list") <(rpm -qpl "$rpm" | files)
|
||||
dpkg-deb --info "$deb"
|
||||
rpm -qpi "$rpm"
|
||||
echo "rpm requires:"; rpm -qpR "$rpm"
|
||||
# The release notes live on GitHub, so the package has no Debian changelog (a native
|
||||
# package built upstream, not by a distribution).
|
||||
lintian --info --fail-on error --suppress-tags no-changelog "$deb"
|
||||
ldd target/release/fieldcraft
|
||||
for appimage in dist/release/*.AppImage; do
|
||||
chmod +x "$appimage"
|
||||
APPIMAGE_EXTRACT_AND_RUN=1 "$appimage" --version
|
||||
done
|
||||
- name: Install the .deb and .rpm in containers
|
||||
run: |
|
||||
# The oldest supported Ubuntu (the build's glibc) and a current Fedora. Recommended and
|
||||
# weak dependencies (GPU drivers) are skipped to keep it quick; the hard ones must resolve.
|
||||
# Both images leave out documentation when installing (dpkg path-exclude, dnf nodocs), so
|
||||
# the licences are checked in the package's file list rather than on disk.
|
||||
docker run --rm -v "$PWD/dist/release:/dist:ro" ubuntu:22.04 bash -euxc '
|
||||
apt-get update -qq
|
||||
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends /dist/*.deb
|
||||
fieldcraft-cli --version
|
||||
fieldcraft --version
|
||||
dpkg -L fieldcraft | grep -Fx /usr/share/doc/fieldcraft/THIRD-PARTY-LICENSES.txt'
|
||||
docker run --rm -v "$PWD/dist/release:/dist:ro" fedora:44 bash -euxc '
|
||||
dnf install -y -q --setopt=install_weak_deps=False /dist/*.rpm
|
||||
fieldcraft-cli --version
|
||||
fieldcraft --version
|
||||
rpm -ql fieldcraft | grep -Fx /usr/share/doc/fieldcraft/THIRD-PARTY-LICENSES.txt
|
||||
dnf install -y -q rpmlint
|
||||
rpmlint /dist/*.rpm || true'
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: release-linux-x86_64
|
||||
@@ -171,6 +217,9 @@ jobs:
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
- name: Build and package (zip)
|
||||
shell: pwsh
|
||||
env:
|
||||
# The analytics project key (docs/privacy.md), built in; never printed.
|
||||
FIELDCRAFT_POSTHOG_KEY: ${{ secrets.POSTHOG_KEY }}
|
||||
run: ./packaging/windows/package.ps1
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
@@ -197,21 +246,54 @@ jobs:
|
||||
pattern: release-*
|
||||
path: artifacts
|
||||
merge-multiple: true
|
||||
- name: Check the set, checksums and notes
|
||||
- name: Check the set and write the checksums
|
||||
run: |
|
||||
for f in "fieldcraft-$VERSION-macos-universal.dmg" "fieldcraft-cli-$VERSION-macos-universal.zip" \
|
||||
"fieldcraft-$VERSION-linux-x86_64.tar.gz" "fieldcraft-$VERSION-linux-x86_64.AppImage" \
|
||||
"fieldcraft_${VERSION}_amd64.deb" "fieldcraft-$VERSION.x86_64.rpm" \
|
||||
"fieldcraft-$VERSION-windows-x64.zip"; do
|
||||
test -s "artifacts/$f" || { echo "::error::missing $f"; exit 1; }
|
||||
done
|
||||
(cd artifacts && sha256sum -- * | tee SHA256SUMS.txt)
|
||||
- name: Sign SHA256SUMS.txt with the release key (skipped without FIELDCRAFT_SIGNING_KEY)
|
||||
id: sign
|
||||
env:
|
||||
FIELDCRAFT_SIGNING_KEY: ${{ secrets.FIELDCRAFT_SIGNING_KEY }}
|
||||
# rsign2 (MIT), a minisign-compatible signer, pinned.
|
||||
RSIGN_VERSION: 0.6.7
|
||||
run: |
|
||||
if [ -z "$FIELDCRAFT_SIGNING_KEY" ]; then
|
||||
echo "::warning::FIELDCRAFT_SIGNING_KEY is not set: SHA256SUMS.txt is not signed, so the app cannot install this release itself (docs/releasing.md)"
|
||||
echo "signed=false" >>"$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
cargo install --locked --quiet --root "$RUNNER_TEMP/rsign" rsign2 --version "$RSIGN_VERSION"
|
||||
rsign="$RUNNER_TEMP/rsign/bin/rsign"
|
||||
key="$RUNNER_TEMP/release.key"
|
||||
(umask 077 && printf '%s\n' "$FIELDCRAFT_SIGNING_KEY" >"$key")
|
||||
"$rsign" sign -W -s "$key" -t "FieldCraft v$VERSION SHA256SUMS.txt" -x artifacts/SHA256SUMS.txt.minisig artifacts/SHA256SUMS.txt
|
||||
rm -f "$key"
|
||||
# The signature must verify with the public key the app is built with.
|
||||
public="$(sed -n 's/^pub const PUBLIC_KEY: &str = "\(.*\)";$/\1/p' crates/update/src/lib.rs)"
|
||||
"$rsign" verify -q -P "$public" -x artifacts/SHA256SUMS.txt.minisig artifacts/SHA256SUMS.txt
|
||||
echo "signed=true" >>"$GITHUB_OUTPUT"
|
||||
- name: Write the notes
|
||||
env:
|
||||
SIGNED: ${{ steps.sign.outputs.signed }}
|
||||
run: |
|
||||
# The macOS paragraph says how the app was signed (packaging/macos/package.sh).
|
||||
case "$MACOS_SIGNING" in
|
||||
notarized) macos="The macOS app is signed with a Developer ID and notarized by Apple." ;;
|
||||
signed) macos="The macOS app is signed with a Developer ID but **not notarized**: the first time, right-click \`FieldCraft.app\` in Applications and choose **Open**." ;;
|
||||
*) macos="The macOS app is **ad-hoc signed and not notarized**: macOS blocks the first launch. Right-click \`FieldCraft.app\` in Applications and choose **Open** (then **Open** again), or run \`xattr -dr com.apple.quarantine /Applications/FieldCraft.app\`." ;;
|
||||
esac
|
||||
awk -v v="$VERSION" -v m="$macos" '{ gsub(/\{version\}/, v); gsub(/\{macos_signing\}/, m); print }' \
|
||||
# The updates paragraph says whether the app can install this release itself.
|
||||
if [ "$SIGNED" = true ]; then
|
||||
updates="\`SHA256SUMS.txt\` is signed with the FieldCraft release key (\`SHA256SUMS.txt.minisig\`), so FieldCraft's Help › Check for Updates can verify and install this release."
|
||||
else
|
||||
updates="This release's \`SHA256SUMS.txt\` is **not signed**: FieldCraft's in-app updates can't verify it and won't install it; download it from this page instead."
|
||||
fi
|
||||
awk -v v="$VERSION" -v m="$macos" -v u="$updates" '{ gsub(/\{version\}/, v); gsub(/\{macos_signing\}/, m); gsub(/\{update_signing\}/, u); print }' \
|
||||
.github/release-notes.md >notes.md
|
||||
cat notes.md >>"$GITHUB_STEP_SUMMARY"
|
||||
- name: Upload the dry-run artifacts
|
||||
|
||||
@@ -23,12 +23,20 @@ is committed and listed here with its exports.
|
||||
| docs/media/examples/heated-bracket.png | FieldCraft contributors | Original: the FieldCraft window captured (`ui.capture`) with the solved heated-bracket sample (docs/examples.md) | MIT OR Apache-2.0 |
|
||||
| docs/media/examples/bracket-hex.png | FieldCraft contributors | Original: the FieldCraft window captured (`ui.capture`) with the solved bracket-hex sample (docs/examples.md) | MIT OR Apache-2.0 |
|
||||
| docs/media/examples/crank-arm.png | FieldCraft contributors | Original: the FieldCraft window captured (`ui.capture`) with the solved crank-arm sample (docs/examples.md) | MIT OR Apache-2.0 |
|
||||
| docs/media/examples/crank-mirror.png | FieldCraft contributors | Original: the FieldCraft window captured (`ui.capture`) with the solved crank-mirror sample (docs/examples.md) | MIT OR Apache-2.0 |
|
||||
| crates/ui-egui/thumbnails/bracket-hex.png | FieldCraft contributors | Original: the viewport of docs/media/examples/bracket-hex.png cropped to the model and scaled to 320 px wide (ImageMagick, 128-colour palette), the bracket-hex sample's thumbnail on the Start card | MIT OR Apache-2.0 |
|
||||
| crates/ui-egui/thumbnails/crank-arm.png | FieldCraft contributors | Original: the viewport of docs/media/examples/crank-arm.png cropped to the model and scaled to 320 px wide (ImageMagick, 128-colour palette), the crank-arm sample's thumbnail on the Start card | MIT OR Apache-2.0 |
|
||||
| crates/ui-egui/thumbnails/crank-mirror.png | FieldCraft contributors | Original: the viewport of docs/media/examples/crank-mirror.png cropped to the model and scaled to 320 px wide (ImageMagick, 128-colour palette), the crank-mirror sample's thumbnail on the Start card | MIT OR Apache-2.0 |
|
||||
| crates/ui-egui/thumbnails/drop-test.png | FieldCraft contributors | Original: the viewport of docs/media/examples/drop-test.png cropped to the model and scaled to 320 px wide (ImageMagick, 128-colour palette), the drop-test sample's thumbnail on the Start card | MIT OR Apache-2.0 |
|
||||
| crates/ui-egui/thumbnails/heated-bracket.png | FieldCraft contributors | Original: the viewport of docs/media/examples/heated-bracket.png cropped to the model and scaled to 320 px wide (ImageMagick, 128-colour palette), the heated-bracket sample's thumbnail on the Start card | MIT OR Apache-2.0 |
|
||||
| crates/ui-egui/thumbnails/rubber-seal.png | FieldCraft contributors | Original: the viewport of docs/media/examples/rubber-seal.png cropped to the model and scaled to 320 px wide (ImageMagick, 128-colour palette), the rubber-seal sample's thumbnail on the Start card | MIT OR Apache-2.0 |
|
||||
| crates/decks/tests/golden/nastran/*.bdf | FieldCraft contributors | Written by our Nastran writer from our own test models (crates/decks/tests/nastran.rs) | MIT OR Apache-2.0 |
|
||||
| assets/icons/assembly.instance.svg, assets/icons/assembly.instance.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/assembly.instance.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/deck.read.svg, assets/icons/deck.read.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/deck.read.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/deck.write.abaqus.svg, assets/icons/deck.write.abaqus.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/deck.write.abaqus.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/deck.write.lsdyna.svg, assets/icons/deck.write.lsdyna.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/deck.write.lsdyna.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/deck.write.nastran.svg, assets/icons/deck.write.nastran.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/deck.write.nastran.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/diagnostics.bug_report.svg, assets/icons/diagnostics.bug_report.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/diagnostics.bug_report.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/edit.redo.svg, assets/icons/edit.redo.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/edit.redo.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/edit.undo.svg, assets/icons/edit.undo.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/edit.undo.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/file.open.svg, assets/icons/file.open.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/file.open.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
@@ -37,6 +45,8 @@ is committed and listed here with its exports.
|
||||
| assets/icons/file.save.svg, assets/icons/file.save.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/file.save.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/geometry.bodies.svg, assets/icons/geometry.bodies.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/geometry.bodies.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/geometry.datum.svg, assets/icons/geometry.datum.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/geometry.datum.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/geometry.datum.axis.svg, assets/icons/geometry.datum.axis.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/geometry.datum.axis.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/geometry.datum.point.svg, assets/icons/geometry.datum.point.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/geometry.datum.point.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/geometry.import.mesh.svg, assets/icons/geometry.import.mesh.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/geometry.import.mesh.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/geometry.midsurface.svg, assets/icons/geometry.midsurface.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/geometry.midsurface.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/geometry.open.svg, assets/icons/geometry.open.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/geometry.open.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
@@ -56,11 +66,10 @@ is committed and listed here with its exports.
|
||||
| assets/icons/mesh.element.add.svg, assets/icons/mesh.element.add.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.element.add.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.hex.decompose.svg, assets/icons/mesh.hex.decompose.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.hex.decompose.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.hex.dominant.svg, assets/icons/mesh.hex.dominant.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.hex.dominant.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.hex.blocks.svg, assets/icons/mesh.hex.blocks.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.hex.blocks.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.hex.mapped.svg, assets/icons/mesh.hex.mapped.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.hex.mapped.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.cells.svg, assets/icons/mesh.cells.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.cells.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.hex.generate.svg, assets/icons/mesh.hex.generate.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.hex.generate.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.hex.octree.svg, assets/icons/mesh.hex.octree.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.hex.octree.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.hex.polycube.svg, assets/icons/mesh.hex.polycube.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.hex.polycube.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.hex.sweep.svg, assets/icons/mesh.hex.sweep.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.hex.sweep.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.import.orphan.svg, assets/icons/mesh.import.orphan.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.import.orphan.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.layers.svg, assets/icons/mesh.layers.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.layers.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.node.add.svg, assets/icons/mesh.node.add.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.node.add.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
@@ -71,7 +80,7 @@ is committed and listed here with its exports.
|
||||
| assets/icons/mesh.region.remesh.svg, assets/icons/mesh.region.remesh.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.region.remesh.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.size.adapt.svg, assets/icons/mesh.size.adapt.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.size.adapt.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.size.global.svg, assets/icons/mesh.size.global.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.size.global.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.size.seed.svg, assets/icons/mesh.size.seed.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.size.seed.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.seed.edge.svg, assets/icons/mesh.seed.edge.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.seed.edge.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.smooth.svg, assets/icons/mesh.smooth.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.smooth.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.surface.check.svg, assets/icons/mesh.surface.check.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.surface.check.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/mesh.tag.svg, assets/icons/mesh.tag.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.tag.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
@@ -141,6 +150,7 @@ is committed and listed here with its exports.
|
||||
| assets/icons/ui.sun.svg, assets/icons/ui.sun.vectorcraft | FieldCraft contributors | Original interface icon (navigation bar, title bar, browser) drawn with VectorCraft from `assets/icons/src/ui.sun.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/ui.views.svg, assets/icons/ui.views.vectorcraft | FieldCraft contributors | Original interface icon (navigation bar, title bar, browser) drawn with VectorCraft from `assets/icons/src/ui.views.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/ui.zoom.svg, assets/icons/ui.zoom.vectorcraft | FieldCraft contributors | Original interface icon (navigation bar, title bar, browser) drawn with VectorCraft from `assets/icons/src/ui.zoom.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/icons/view.show_all.svg, assets/icons/view.show_all.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/view.show_all.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
|
||||
| assets/app-icon/icon.vectorcraft, assets/app-icon/icon.svg, assets/app-icon/icon.png | FieldCraft contributors | Original application icon (a hexahedral-meshed cube with a banded colour fringe on its faces on a rounded-square backdrop), drawn with VectorCraft by `cargo xtask app-icon` (xtask/src/app_icon.rs); editable source, SVG and 1024 × 1024 PNG export | MIT OR Apache-2.0 |
|
||||
| assets/app-icon/icon-small.vectorcraft, assets/app-icon/icon-small.svg, assets/app-icon/icon-small.png | FieldCraft contributors | Original simplified application icon for 16–32 px (the fringe cube alone; no mesh or floor grid), drawn with VectorCraft by `cargo xtask app-icon` (xtask/src/app_icon.rs) | MIT OR Apache-2.0 |
|
||||
| assets/app-icon/layers/01-floor.vectorcraft, assets/app-icon/FieldCraft.icon/Assets/01-floor.svg | FieldCraft contributors | Original isometric floor grid with a radial fade (Default appearance), drawn with VectorCraft by `cargo xtask app-icon` (xtask/src/app_icon.rs) | MIT OR Apache-2.0 |
|
||||
@@ -173,13 +183,16 @@ is committed and listed here with its exports.
|
||||
| crates/geometry/src/tagged_mesh.rs (package and part reading, transforms, units, caps) | SolidCraft `crates/io/src/threemf.rs` | MIT OR Apache-2.0 |
|
||||
| crates/render/src/camera.rs, crates/render/src/raster.rs | SolidCraft `crates/render/src/camera.rs`, `raster.rs` | MIT OR Apache-2.0 |
|
||||
| crates/ui-egui/src/gpu.rs, crates/ui-egui/src/theme.rs (tokens and their values), crates/ui-egui/src/control.rs, crates/ui-egui/src/lib.rs (input injection, screenshots), crates/ui-egui/src/toolbar.rs (workspace switcher, tabs, panels with drop-downs, fitting), crates/ui-egui/src/appbar.rs (application bar; the mark is drawn from assets/app-icon/icon-small.svg's coordinates), crates/ui-egui/src/titlebar.rs (caption buttons, drag and resize zones; SolidCraft took it from VectorCraft), crates/ui-egui/src/frame.rs (windows, heading bands), crates/ui-egui/src/browser.rs (row drawing), crates/ui-egui/src/palette.rs (command line and search), crates/ui-egui/src/timeline.rs (timeline strip, transport), crates/ui-egui/src/viewport.rs (navigation bar, orientation gizmo), crates/ui-egui/src/files.rs (background opening, file pickers as host services) | SolidCraft `crates/ui-egui/src/` (titlebar.rs also VectorCraft `crates/ui-egui/src/titlebar.rs`) | MIT OR Apache-2.0 |
|
||||
| crates/ui-egui/src/navigation.rs (navigation presets and bindings), crates/ui-egui/src/viewport.rs (orbit about the point under the cursor, or the drawn centre from empty space; Ctrl + left drag orbits) | SolidCraft `crates/ui-egui/src/prefs.rs` (`NavPreset`, `NavBinding`, `NAV_PRESETS`, `orbit`) | MIT OR Apache-2.0 |
|
||||
| crates/ui-egui/src/fields.rs (form rows: a label column of fixed width, then the field) | SolidCraft `crates/ui-egui/src/dialogs.rs` | MIT OR Apache-2.0 |
|
||||
| crates/io/src/fs.rs (atomic writes) | SolidCraft `crates/io/src/safe_write.rs` | MIT OR Apache-2.0 |
|
||||
| crates/io/src/recovery.rs (recovery folder, entries, locks) | SolidCraft `crates/engine/src/recovery.rs` | MIT OR Apache-2.0 |
|
||||
| crates/engine/src/crash.rs, crates/engine/src/crash_tests.rs (crash reports: panic hook, locked command journal, unclean-exit detection, report folders and limits, replay), apps/fieldcraft-cli/src/crashes.rs, docs/crash-reports.md (structure) | SolidCraft `crates/engine/src/crash.rs`, `crash_tests.rs`, `apps/solidcraft-cli/src/crashes.rs`, `docs/crash-reports.md` | MIT OR Apache-2.0 |
|
||||
| apps/fieldcraft/src/control_server.rs | SolidCraft `apps/solidcraft/src/control_server.rs` | MIT OR Apache-2.0 |
|
||||
| crates/mcp/src/ (JSON-RPC framing, MCP lifecycle, tool schema checks, the control-channel backend, base64) | SolidCraft `crates/mcp/src/` | MIT OR Apache-2.0 |
|
||||
| crates/io/src/roots.rs (the rules of read and write roots) | VectorCraft's automation roots (docs/mcp.md there) | MIT OR Apache-2.0 |
|
||||
| packaging/env.sh, packaging/.shellcheckrc, packaging/macos/package.sh, packaging/macos/Info.plist.in, packaging/linux/package.sh, packaging/linux/AppRun, packaging/windows/package.ps1 | SolidCraft `packaging/` and VectorCraft `packaging/` (signing and notarization in macos/package.sh) | MIT OR Apache-2.0 |
|
||||
| apps/fieldcraft/Cargo.toml (the run-time dependency lists of `[package.metadata.deb]` and `[package.metadata.generate-rpm]`) | SolidCraft `packaging/linux/nfpm.yaml` | MIT OR Apache-2.0 |
|
||||
| packaging/macos/import-cert.sh | VectorCraft `packaging/macos/import-cert.sh` | MIT OR Apache-2.0 |
|
||||
| packaging/windows/check-exe.ps1 | SolidCraft `packaging/windows/check-icon.ps1` | MIT OR Apache-2.0 |
|
||||
| apps/fieldcraft-web/ (the web runner, browser file services and downloads, Trunk configuration, index.html) | VectorCraft `apps/vectorcraft-web/` and SolidCraft `apps/solidcraft-web/` | MIT OR Apache-2.0 |
|
||||
|
||||
@@ -431,6 +431,12 @@ version = "0.22.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.23.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
|
||||
|
||||
[[package]]
|
||||
name = "bit-set"
|
||||
version = "0.10.0"
|
||||
@@ -661,6 +667,16 @@ dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cipher"
|
||||
version = "0.4.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
|
||||
dependencies = [
|
||||
"crypto-common 0.1.7",
|
||||
"inout",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clipboard-win"
|
||||
version = "5.4.1"
|
||||
@@ -731,6 +747,16 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "core-foundation"
|
||||
version = "0.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
|
||||
dependencies = [
|
||||
"core-foundation-sys",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "core-foundation-sys"
|
||||
version = "0.8.7"
|
||||
@@ -744,7 +770,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081"
|
||||
dependencies = [
|
||||
"bitflags 1.3.2",
|
||||
"core-foundation",
|
||||
"core-foundation 0.9.4",
|
||||
"core-graphics-types",
|
||||
"foreign-types",
|
||||
"libc",
|
||||
@@ -757,7 +783,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf"
|
||||
dependencies = [
|
||||
"bitflags 1.3.2",
|
||||
"core-foundation",
|
||||
"core-foundation 0.9.4",
|
||||
"libc",
|
||||
]
|
||||
|
||||
@@ -846,6 +872,12 @@ dependencies = [
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ct-codecs"
|
||||
version = "1.1.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8fd9f3db6f2cfef61c10613071955154ffdc9e515daebff26de4b54e35038fdd"
|
||||
|
||||
[[package]]
|
||||
name = "cursor-icon"
|
||||
version = "1.2.0"
|
||||
@@ -890,6 +922,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer 0.10.4",
|
||||
"crypto-common 0.1.7",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1019,7 +1052,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui-wgpu"
|
||||
version = "0.36.2"
|
||||
source = "git+https://github.com/bherbruck/solidcraft?rev=de1479029dd6821cffd28b70688a58e7f61f0cfd#de1479029dd6821cffd28b70688a58e7f61f0cfd"
|
||||
source = "git+https://github.com/bherbruck/solidcraft?rev=a629236650c44ee73edf36fab0dcd2385103a610#a629236650c44ee73edf36fab0dcd2385103a610"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -1237,7 +1270,7 @@ checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693"
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft"
|
||||
version = "0.5.7"
|
||||
version = "0.5.9"
|
||||
dependencies = [
|
||||
"eframe",
|
||||
"egui",
|
||||
@@ -1245,24 +1278,29 @@ dependencies = [
|
||||
"fieldcraft-engine",
|
||||
"fieldcraft-io",
|
||||
"fieldcraft-ui-egui",
|
||||
"fieldcraft-update",
|
||||
"getrandom 0.3.4",
|
||||
"log",
|
||||
"rfd",
|
||||
"rustls",
|
||||
"serde_json",
|
||||
"ureq",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft-cli"
|
||||
version = "0.5.7"
|
||||
version = "0.5.9"
|
||||
dependencies = [
|
||||
"fieldcraft-engine",
|
||||
"fieldcraft-io",
|
||||
"fieldcraft-mcp",
|
||||
"fieldcraft-update",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft-decks"
|
||||
version = "0.5.7"
|
||||
version = "0.5.9"
|
||||
dependencies = [
|
||||
"fieldcraft-model",
|
||||
"serde_json",
|
||||
@@ -1271,7 +1309,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft-engine"
|
||||
version = "0.5.7"
|
||||
version = "0.5.9"
|
||||
dependencies = [
|
||||
"fieldcraft-decks",
|
||||
"fieldcraft-explicit",
|
||||
@@ -1284,7 +1322,9 @@ dependencies = [
|
||||
"fieldcraft-parallel",
|
||||
"fieldcraft-render",
|
||||
"fieldcraft-solver",
|
||||
"fieldcraft-update",
|
||||
"log",
|
||||
"png",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1293,7 +1333,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft-explicit"
|
||||
version = "0.5.7"
|
||||
version = "0.5.9"
|
||||
dependencies = [
|
||||
"fieldcraft-fem",
|
||||
"fieldcraft-model",
|
||||
@@ -1304,7 +1344,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft-fem"
|
||||
version = "0.5.7"
|
||||
version = "0.5.9"
|
||||
dependencies = [
|
||||
"fieldcraft-model",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1312,7 +1352,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft-geometry"
|
||||
version = "0.5.7"
|
||||
version = "0.5.9"
|
||||
dependencies = [
|
||||
"fieldcraft-model",
|
||||
"quick-xml",
|
||||
@@ -1328,7 +1368,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft-io"
|
||||
version = "0.5.7"
|
||||
version = "0.5.9"
|
||||
dependencies = [
|
||||
"fieldcraft-model",
|
||||
"log",
|
||||
@@ -1341,7 +1381,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft-lbm"
|
||||
version = "0.5.7"
|
||||
version = "0.5.9"
|
||||
dependencies = [
|
||||
"fieldcraft-mesh",
|
||||
"fieldcraft-model",
|
||||
@@ -1351,7 +1391,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft-mcp"
|
||||
version = "0.5.7"
|
||||
version = "0.5.9"
|
||||
dependencies = [
|
||||
"fieldcraft-engine",
|
||||
"fieldcraft-io",
|
||||
@@ -1362,7 +1402,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft-mesh"
|
||||
version = "0.5.7"
|
||||
version = "0.5.9"
|
||||
dependencies = [
|
||||
"fieldcraft-model",
|
||||
"num-bigint",
|
||||
@@ -1374,7 +1414,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft-model"
|
||||
version = "0.5.7"
|
||||
version = "0.5.9"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -1383,14 +1423,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft-parallel"
|
||||
version = "0.5.7"
|
||||
version = "0.5.9"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft-render"
|
||||
version = "0.5.7"
|
||||
version = "0.5.9"
|
||||
dependencies = [
|
||||
"fieldcraft-model",
|
||||
"png",
|
||||
@@ -1400,7 +1440,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft-solver"
|
||||
version = "0.5.7"
|
||||
version = "0.5.9"
|
||||
dependencies = [
|
||||
"fieldcraft-fem",
|
||||
"fieldcraft-mesh",
|
||||
@@ -1412,7 +1452,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft-testkit"
|
||||
version = "0.5.7"
|
||||
version = "0.5.9"
|
||||
dependencies = [
|
||||
"fieldcraft-engine",
|
||||
"fieldcraft-geometry",
|
||||
@@ -1423,7 +1463,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft-ui-egui"
|
||||
version = "0.5.7"
|
||||
version = "0.5.9"
|
||||
dependencies = [
|
||||
"craft-ui",
|
||||
"egui",
|
||||
@@ -1434,17 +1474,36 @@ dependencies = [
|
||||
"fieldcraft-geometry",
|
||||
"fieldcraft-model",
|
||||
"fieldcraft-render",
|
||||
"fieldcraft-update",
|
||||
"log",
|
||||
"png",
|
||||
"resvg",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft-web"
|
||||
version = "0.5.7"
|
||||
name = "fieldcraft-update"
|
||||
version = "0.5.9"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"flate2",
|
||||
"log",
|
||||
"minisign",
|
||||
"minisign-verify",
|
||||
"rustls",
|
||||
"serde_json",
|
||||
"sha2 0.11.1",
|
||||
"tar",
|
||||
"thiserror 2.0.21",
|
||||
"ureq",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fieldcraft-web"
|
||||
version = "0.5.9"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"eframe",
|
||||
"egui",
|
||||
"fieldcraft-engine",
|
||||
@@ -1459,6 +1518,16 @@ dependencies = [
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "filetime"
|
||||
version = "0.2.29"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "find-msvc-tools"
|
||||
version = "0.1.14"
|
||||
@@ -1631,8 +1700,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"js-sys",
|
||||
"libc",
|
||||
"r-efi 6.0.0",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1819,6 +1890,31 @@ version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
|
||||
|
||||
[[package]]
|
||||
name = "hmac"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
|
||||
dependencies = [
|
||||
"digest 0.10.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "http"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"itoa",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "httparse"
|
||||
version = "1.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
|
||||
|
||||
[[package]]
|
||||
name = "hybrid-array"
|
||||
version = "0.4.15"
|
||||
@@ -1864,6 +1960,8 @@ dependencies = [
|
||||
"num-traits",
|
||||
"png",
|
||||
"tiff",
|
||||
"zune-core",
|
||||
"zune-jpeg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1882,6 +1980,15 @@ dependencies = [
|
||||
"hashbrown 0.17.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "inout"
|
||||
version = "0.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itertools"
|
||||
version = "0.13.0"
|
||||
@@ -2101,7 +2208,7 @@ checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
|
||||
[[package]]
|
||||
name = "matext4cgmath"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/bherbruck/solidcraft?rev=de1479029dd6821cffd28b70688a58e7f61f0cfd#de1479029dd6821cffd28b70688a58e7f61f0cfd"
|
||||
source = "git+https://github.com/bherbruck/solidcraft?rev=a629236650c44ee73edf36fab0dcd2385103a610#a629236650c44ee73edf36fab0dcd2385103a610"
|
||||
dependencies = [
|
||||
"cgmath",
|
||||
"katexit",
|
||||
@@ -2132,6 +2239,24 @@ dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "minisign"
|
||||
version = "0.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aefd422a7a8b5efced01cd7cdf3771e62ebecbc90e3d27695002d3af6af94586"
|
||||
dependencies = [
|
||||
"ct-codecs",
|
||||
"getrandom 0.4.3",
|
||||
"rpassword",
|
||||
"scrypt",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "minisign-verify"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "871285dc19d8d0ebe0eef3d0e99a205f2a71363b122632cbbfa4a6c370a960ce"
|
||||
|
||||
[[package]]
|
||||
name = "miniz_oxide"
|
||||
version = "0.8.9"
|
||||
@@ -2624,6 +2749,12 @@ version = "1.21.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||
|
||||
[[package]]
|
||||
name = "openssl-probe"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
|
||||
|
||||
[[package]]
|
||||
name = "orbclient"
|
||||
version = "0.3.55"
|
||||
@@ -2682,6 +2813,16 @@ dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pbkdf2"
|
||||
version = "0.12.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2"
|
||||
dependencies = [
|
||||
"digest 0.10.7",
|
||||
"hmac",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "peniko"
|
||||
version = "0.6.1"
|
||||
@@ -3145,6 +3286,20 @@ dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ring"
|
||||
version = "0.17.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"cfg-if",
|
||||
"getrandom 0.2.17",
|
||||
"libc",
|
||||
"untrusted",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "robust"
|
||||
version = "1.2.0"
|
||||
@@ -3160,6 +3315,27 @@ dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rpassword"
|
||||
version = "7.5.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2da316a15f47e3d053de9cb2c439650bd8fa4aaeb9365f2e5f27f492ff73c196"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"rtoolbox",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rtoolbox"
|
||||
version = "0.0.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9a1efe12a1469752d0e6ff5ebec0b6ef4924cc5c4c71046b0ec730040535819d"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustc-hash"
|
||||
version = "1.1.0"
|
||||
@@ -3207,12 +3383,95 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls"
|
||||
version = "0.23.46"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
|
||||
dependencies = [
|
||||
"log",
|
||||
"once_cell",
|
||||
"ring",
|
||||
"rustls-pki-types",
|
||||
"rustls-webpki",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-native-certs"
|
||||
version = "0.8.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4"
|
||||
dependencies = [
|
||||
"openssl-probe",
|
||||
"rustls-pki-types",
|
||||
"schannel",
|
||||
"security-framework",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-pki-types"
|
||||
version = "1.15.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
|
||||
dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-platform-verifier"
|
||||
version = "0.7.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98"
|
||||
dependencies = [
|
||||
"core-foundation 0.10.1",
|
||||
"core-foundation-sys",
|
||||
"jni",
|
||||
"log",
|
||||
"once_cell",
|
||||
"rustls",
|
||||
"rustls-native-certs",
|
||||
"rustls-platform-verifier-android",
|
||||
"rustls-webpki",
|
||||
"security-framework",
|
||||
"security-framework-sys",
|
||||
"webpki-root-certs",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-platform-verifier-android"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f"
|
||||
|
||||
[[package]]
|
||||
name = "rustls-webpki"
|
||||
version = "0.103.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"
|
||||
dependencies = [
|
||||
"ring",
|
||||
"rustls-pki-types",
|
||||
"untrusted",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustversion"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
|
||||
|
||||
[[package]]
|
||||
name = "salsa20"
|
||||
version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "97a22f5af31f73a954c10289c93e8a50cc23d971e80ee446f1f6f7137a088213"
|
||||
dependencies = [
|
||||
"cipher",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "same-file"
|
||||
version = "1.0.6"
|
||||
@@ -3222,6 +3481,15 @@ dependencies = [
|
||||
"winapi-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "schannel"
|
||||
version = "0.1.29"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "scoped-tls"
|
||||
version = "1.0.1"
|
||||
@@ -3234,6 +3502,40 @@ version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
||||
|
||||
[[package]]
|
||||
name = "scrypt"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0516a385866c09368f0b5bcd1caff3366aace790fcd46e2bb032697bb172fd1f"
|
||||
dependencies = [
|
||||
"pbkdf2",
|
||||
"salsa20",
|
||||
"sha2 0.10.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "security-framework"
|
||||
version = "3.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"core-foundation 0.10.1",
|
||||
"core-foundation-sys",
|
||||
"libc",
|
||||
"security-framework-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "security-framework-sys"
|
||||
version = "2.17.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"
|
||||
dependencies = [
|
||||
"core-foundation-sys",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "self_cell"
|
||||
version = "1.3.0"
|
||||
@@ -3489,8 +3791,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-doc"
|
||||
version = "0.8.0"
|
||||
source = "git+https://github.com/bherbruck/solidcraft?rev=de1479029dd6821cffd28b70688a58e7f61f0cfd#de1479029dd6821cffd28b70688a58e7f61f0cfd"
|
||||
version = "0.11.0"
|
||||
source = "git+https://github.com/bherbruck/solidcraft?rev=a629236650c44ee73edf36fab0dcd2385103a610#a629236650c44ee73edf36fab0dcd2385103a610"
|
||||
dependencies = [
|
||||
"log",
|
||||
"serde",
|
||||
@@ -3498,6 +3800,7 @@ dependencies = [
|
||||
"sha2 0.10.9",
|
||||
"solidcraft-geom",
|
||||
"solidcraft-kernel",
|
||||
"solidcraft-render",
|
||||
"solidcraft-sketch",
|
||||
"thiserror 2.0.21",
|
||||
"web-time",
|
||||
@@ -3505,8 +3808,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-engine"
|
||||
version = "0.8.0"
|
||||
source = "git+https://github.com/bherbruck/solidcraft?rev=de1479029dd6821cffd28b70688a58e7f61f0cfd#de1479029dd6821cffd28b70688a58e7f61f0cfd"
|
||||
version = "0.11.0"
|
||||
source = "git+https://github.com/bherbruck/solidcraft?rev=a629236650c44ee73edf36fab0dcd2385103a610#a629236650c44ee73edf36fab0dcd2385103a610"
|
||||
dependencies = [
|
||||
"log",
|
||||
"serde",
|
||||
@@ -3522,8 +3825,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-geom"
|
||||
version = "0.8.0"
|
||||
source = "git+https://github.com/bherbruck/solidcraft?rev=de1479029dd6821cffd28b70688a58e7f61f0cfd#de1479029dd6821cffd28b70688a58e7f61f0cfd"
|
||||
version = "0.11.0"
|
||||
source = "git+https://github.com/bherbruck/solidcraft?rev=a629236650c44ee73edf36fab0dcd2385103a610#a629236650c44ee73edf36fab0dcd2385103a610"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -3531,8 +3834,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-io"
|
||||
version = "0.8.0"
|
||||
source = "git+https://github.com/bherbruck/solidcraft?rev=de1479029dd6821cffd28b70688a58e7f61f0cfd#de1479029dd6821cffd28b70688a58e7f61f0cfd"
|
||||
version = "0.11.0"
|
||||
source = "git+https://github.com/bherbruck/solidcraft?rev=a629236650c44ee73edf36fab0dcd2385103a610#a629236650c44ee73edf36fab0dcd2385103a610"
|
||||
dependencies = [
|
||||
"quick-xml",
|
||||
"serde",
|
||||
@@ -3547,13 +3850,15 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-kernel"
|
||||
version = "0.8.0"
|
||||
source = "git+https://github.com/bherbruck/solidcraft?rev=de1479029dd6821cffd28b70688a58e7f61f0cfd#de1479029dd6821cffd28b70688a58e7f61f0cfd"
|
||||
version = "0.11.0"
|
||||
source = "git+https://github.com/bherbruck/solidcraft?rev=a629236650c44ee73edf36fab0dcd2385103a610#a629236650c44ee73edf36fab0dcd2385103a610"
|
||||
dependencies = [
|
||||
"log",
|
||||
"rayon",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"solidcraft-geom",
|
||||
"spade",
|
||||
"thiserror 2.0.21",
|
||||
"truck-meshalgo",
|
||||
"truck-modeling",
|
||||
@@ -3564,8 +3869,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-render"
|
||||
version = "0.8.0"
|
||||
source = "git+https://github.com/bherbruck/solidcraft?rev=de1479029dd6821cffd28b70688a58e7f61f0cfd#de1479029dd6821cffd28b70688a58e7f61f0cfd"
|
||||
version = "0.11.0"
|
||||
source = "git+https://github.com/bherbruck/solidcraft?rev=a629236650c44ee73edf36fab0dcd2385103a610#a629236650c44ee73edf36fab0dcd2385103a610"
|
||||
dependencies = [
|
||||
"image",
|
||||
"serde",
|
||||
@@ -3574,8 +3879,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-sketch"
|
||||
version = "0.8.0"
|
||||
source = "git+https://github.com/bherbruck/solidcraft?rev=de1479029dd6821cffd28b70688a58e7f61f0cfd#de1479029dd6821cffd28b70688a58e7f61f0cfd"
|
||||
version = "0.11.0"
|
||||
source = "git+https://github.com/bherbruck/solidcraft?rev=a629236650c44ee73edf36fab0dcd2385103a610#a629236650c44ee73edf36fab0dcd2385103a610"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"solidcraft-geom",
|
||||
@@ -3619,6 +3924,12 @@ dependencies = [
|
||||
"float-cmp",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "subtle"
|
||||
version = "2.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
|
||||
|
||||
[[package]]
|
||||
name = "svgtypes"
|
||||
version = "0.16.1"
|
||||
@@ -3661,6 +3972,16 @@ dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tar"
|
||||
version = "0.4.46"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840"
|
||||
dependencies = [
|
||||
"filetime",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tempfile"
|
||||
version = "3.27.0"
|
||||
@@ -3907,7 +4228,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "truck-meshalgo"
|
||||
version = "0.4.0"
|
||||
source = "git+https://github.com/bherbruck/solidcraft?rev=de1479029dd6821cffd28b70688a58e7f61f0cfd#de1479029dd6821cffd28b70688a58e7f61f0cfd"
|
||||
source = "git+https://github.com/bherbruck/solidcraft?rev=a629236650c44ee73edf36fab0dcd2385103a610#a629236650c44ee73edf36fab0dcd2385103a610"
|
||||
dependencies = [
|
||||
"array-macro",
|
||||
"derive_more",
|
||||
@@ -3957,7 +4278,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "truck-shapeops"
|
||||
version = "0.4.0"
|
||||
source = "git+https://github.com/bherbruck/solidcraft?rev=de1479029dd6821cffd28b70688a58e7f61f0cfd#de1479029dd6821cffd28b70688a58e7f61f0cfd"
|
||||
source = "git+https://github.com/bherbruck/solidcraft?rev=a629236650c44ee73edf36fab0dcd2385103a610#a629236650c44ee73edf36fab0dcd2385103a610"
|
||||
dependencies = [
|
||||
"derive_more",
|
||||
"itertools 0.13.0",
|
||||
@@ -3972,7 +4293,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "truck-stepio"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/bherbruck/solidcraft?rev=de1479029dd6821cffd28b70688a58e7f61f0cfd#de1479029dd6821cffd28b70688a58e7f61f0cfd"
|
||||
source = "git+https://github.com/bherbruck/solidcraft?rev=a629236650c44ee73edf36fab0dcd2385103a610#a629236650c44ee73edf36fab0dcd2385103a610"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"truck-geometry",
|
||||
@@ -4053,6 +4374,40 @@ version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
|
||||
|
||||
[[package]]
|
||||
name = "untrusted"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
|
||||
|
||||
[[package]]
|
||||
name = "ureq"
|
||||
version = "3.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9a7ac20be9b7726e0bbdbf974c059676d9acb1cd414961f570a4e8231cacd7fc"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"log",
|
||||
"percent-encoding",
|
||||
"rustls",
|
||||
"rustls-pki-types",
|
||||
"rustls-platform-verifier",
|
||||
"ureq-proto",
|
||||
"utf8-zero",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ureq-proto"
|
||||
version = "0.6.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f86fd172ccca569e458f61b6bdd6220965a9ef36e672a6852953b51a0e1583be"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"http",
|
||||
"httparse",
|
||||
"log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "usvg"
|
||||
version = "0.48.1"
|
||||
@@ -4072,6 +4427,12 @@ dependencies = [
|
||||
"tiny-skia-path",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "utf8-zero"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e"
|
||||
|
||||
[[package]]
|
||||
name = "uuid"
|
||||
version = "1.28.0"
|
||||
@@ -4372,6 +4733,15 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webpki-root-certs"
|
||||
version = "1.0.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b"
|
||||
dependencies = [
|
||||
"rustls-pki-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "weezl"
|
||||
version = "0.1.12"
|
||||
@@ -4860,7 +5230,7 @@ dependencies = [
|
||||
"calloop 0.13.0",
|
||||
"cfg_aliases",
|
||||
"concurrent-queue",
|
||||
"core-foundation",
|
||||
"core-foundation 0.9.4",
|
||||
"core-graphics",
|
||||
"cursor-icon",
|
||||
"dpi",
|
||||
@@ -4986,7 +5356,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
|
||||
|
||||
[[package]]
|
||||
name = "xtask"
|
||||
version = "0.5.7"
|
||||
version = "0.5.9"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
@@ -5117,6 +5487,12 @@ dependencies = [
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zeroize"
|
||||
version = "1.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"
|
||||
|
||||
[[package]]
|
||||
name = "zip"
|
||||
version = "3.0.0"
|
||||
|
||||
@@ -3,7 +3,7 @@ resolver = "3"
|
||||
members = ["crates/*", "apps/*", "xtask"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.5.7"
|
||||
version = "0.5.9"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
@@ -27,6 +27,7 @@ fieldcraft-testkit = { path = "crates/testkit" }
|
||||
fieldcraft-render = { path = "crates/render" }
|
||||
fieldcraft-ui-egui = { path = "crates/ui-egui" }
|
||||
fieldcraft-mcp = { path = "crates/mcp" }
|
||||
fieldcraft-update = { path = "crates/update" }
|
||||
|
||||
# foundation
|
||||
thiserror = "2"
|
||||
@@ -58,13 +59,13 @@ rfd = "0.17"
|
||||
|
||||
# Geometry: SolidCraft's B-rep kernel (MIT OR Apache-2.0), pinned. Only crates/geometry uses it
|
||||
# (plan/adr/0001-libraries.md).
|
||||
solidcraft-geom = { git = "https://github.com/bherbruck/solidcraft", rev = "de1479029dd6821cffd28b70688a58e7f61f0cfd" }
|
||||
solidcraft-kernel = { git = "https://github.com/bherbruck/solidcraft", rev = "de1479029dd6821cffd28b70688a58e7f61f0cfd" }
|
||||
solidcraft-doc = { git = "https://github.com/bherbruck/solidcraft", rev = "de1479029dd6821cffd28b70688a58e7f61f0cfd" }
|
||||
solidcraft-io = { git = "https://github.com/bherbruck/solidcraft", rev = "de1479029dd6821cffd28b70688a58e7f61f0cfd" }
|
||||
solidcraft-geom = { git = "https://github.com/bherbruck/solidcraft", rev = "a629236650c44ee73edf36fab0dcd2385103a610" }
|
||||
solidcraft-kernel = { git = "https://github.com/bherbruck/solidcraft", rev = "a629236650c44ee73edf36fab0dcd2385103a610" }
|
||||
solidcraft-doc = { git = "https://github.com/bherbruck/solidcraft", rev = "a629236650c44ee73edf36fab0dcd2385103a610" }
|
||||
solidcraft-io = { git = "https://github.com/bherbruck/solidcraft", rev = "a629236650c44ee73edf36fab0dcd2385103a610" }
|
||||
# Runs SolidCraft command scripts (the test corpus recipes); only behind fieldcraft-geometry's
|
||||
# `scripts` feature.
|
||||
solidcraft-engine = { git = "https://github.com/bherbruck/solidcraft", rev = "de1479029dd6821cffd28b70688a58e7f61f0cfd" }
|
||||
solidcraft-engine = { git = "https://github.com/bherbruck/solidcraft", rev = "a629236650c44ee73edf36fab0dcd2385103a610" }
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_code = "forbid"
|
||||
@@ -128,10 +129,10 @@ debug = "line-tables-only"
|
||||
# reach a dependent workspace, so FieldCraft applies the same ones from the same pinned commit;
|
||||
# keep this list and the rev in step with SolidCraft's [patch.crates-io].
|
||||
[patch.crates-io]
|
||||
truck-shapeops = { git = "https://github.com/bherbruck/solidcraft", rev = "de1479029dd6821cffd28b70688a58e7f61f0cfd" }
|
||||
truck-stepio = { git = "https://github.com/bherbruck/solidcraft", rev = "de1479029dd6821cffd28b70688a58e7f61f0cfd" }
|
||||
truck-meshalgo = { git = "https://github.com/bherbruck/solidcraft", rev = "de1479029dd6821cffd28b70688a58e7f61f0cfd" }
|
||||
matext4cgmath = { git = "https://github.com/bherbruck/solidcraft", rev = "de1479029dd6821cffd28b70688a58e7f61f0cfd" }
|
||||
truck-shapeops = { git = "https://github.com/bherbruck/solidcraft", rev = "a629236650c44ee73edf36fab0dcd2385103a610" }
|
||||
truck-stepio = { git = "https://github.com/bherbruck/solidcraft", rev = "a629236650c44ee73edf36fab0dcd2385103a610" }
|
||||
truck-meshalgo = { git = "https://github.com/bherbruck/solidcraft", rev = "a629236650c44ee73edf36fab0dcd2385103a610" }
|
||||
matext4cgmath = { git = "https://github.com/bherbruck/solidcraft", rev = "a629236650c44ee73edf36fab0dcd2385103a610" }
|
||||
# egui-wgpu with SolidCraft's fixes (vendor/egui-wgpu there): MSAA clamped to what the device
|
||||
# supports and 1x on OpenGL adapters, so the requested 4x never fails pipeline validation at start.
|
||||
egui-wgpu = { git = "https://github.com/bherbruck/solidcraft", rev = "de1479029dd6821cffd28b70688a58e7f61f0cfd" }
|
||||
egui-wgpu = { git = "https://github.com/bherbruck/solidcraft", rev = "a629236650c44ee73edf36fab0dcd2385103a610" }
|
||||
@@ -98,12 +98,18 @@ Ready-to-solve samples: open one from **File ▸ Samples** (or the start screen)
|
||||
with `fieldcraft --sample NAME`, and press **Solve**. Each opens and solves within half a minute and is checked
|
||||
against a closed form or a reference solution ([docs/examples.md](docs/examples.md)).
|
||||
|
||||
| | | |
|
||||
|---|---|---|
|
||||
|  |  |  |
|
||||
| **Drop test** (`drop-test`): an aluminium bracket dropped 2 m onto a tilted floor; explicit dynamics, the strike's stress waves | **Rubber seal** (`rubber-seal`): a Mooney–Rivlin gasket ring squeezed 25 %; nonlinear static, large strain | **Heated bracket** (`heated-bracket`): a clamped steel bracket heated at one end; steady heat and thermal stress |
|
||||
|  | *No picture yet: the viewport does not draw flow results (M12).* |  |
|
||||
| **Hex-meshed bracket** (`bracket-hex`): the bracket split into 30 cells, meshed all-hex (hex20), von Mises | **Flow past a bracket** (`flow-past`): air past an L-bracket on the floor; lattice Boltzmann flow, the drag and the force on each face | **Bicycle crank arm** (`crank-arm`): an aluminium crank swept all-hex (hex20), a rider's weight on the pedal; root bending within 0.3 % of M/Z |
|
||||
<table>
|
||||
<tr>
|
||||
<td width="33%" valign="top"><img src="docs/media/examples/drop-test.png" alt="Drop test" width="100%"><br><b>Drop test</b> (<code>drop-test</code>): an aluminium bracket dropped 2 m onto a tilted floor; explicit dynamics, the strike's stress waves</td>
|
||||
<td width="33%" valign="top"><img src="docs/media/examples/rubber-seal.png" alt="Rubber seal" width="100%"><br><b>Rubber seal</b> (<code>rubber-seal</code>): a Mooney–Rivlin gasket ring squeezed 25 %; nonlinear static, large strain</td>
|
||||
<td width="33%" valign="top"><img src="docs/media/examples/heated-bracket.png" alt="Heated bracket" width="100%"><br><b>Heated bracket</b> (<code>heated-bracket</code>): a clamped steel bracket heated at one end; steady heat and thermal stress</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="33%" valign="top"><img src="docs/media/examples/bracket-hex.png" alt="Hex-meshed bracket" width="100%"><br><b>Hex-meshed bracket</b> (<code>bracket-hex</code>): the bracket split into 30 cells, meshed all-hex (hex20), von Mises</td>
|
||||
<td width="33%" valign="top"><img src="docs/media/examples/crank-arm.png" alt="Bicycle crank arm" width="100%"><br><b>Bicycle crank arm</b> (<code>crank-arm</code>): an aluminium crank meshed structured all-hex (hex20) from a partitioned half and its mirror image, a rider's weight on the pedal; root bending within 0.3 % of M/Z</td>
|
||||
<td width="33%" valign="top"><i>No picture yet: the viewport does not draw flow results (M12).</i><br><b>Flow past a bracket</b> (<code>flow-past</code>): air past an L-bracket on the floor; lattice Boltzmann flow, the drag and the force on each face</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## Build
|
||||
|
||||
@@ -129,6 +135,16 @@ Rust 1.95 or later, with the `wasm32-unknown-unknown` target for `cargo xtask ci
|
||||
- [Releasing](docs/releasing.md): how a release is built, verified and published
|
||||
- [Contributing](CONTRIBUTING.md) and [agent instructions](AGENTS.md)
|
||||
|
||||
## Privacy
|
||||
|
||||
FieldCraft sends nothing until you agree. The first start asks once whether to share anonymous
|
||||
usage (which tools you use, nothing from your models); Help › Settings… changes it, and
|
||||
`FIELDCRAFT_TELEMETRY=0` turns it off. File names, paths, geometry, model contents, parameter
|
||||
values and messages are never sent: [docs/privacy.md](docs/privacy.md) lists every event and
|
||||
property. Crash reports and the log stay on your computer; Help › Report a Bug opens a GitHub issue
|
||||
you review and submit yourself, with your session or model attached only if you tick them
|
||||
([docs/crash-reports.md](docs/crash-reports.md)).
|
||||
|
||||
## License
|
||||
|
||||
Dual-licensed under [MIT](LICENSE-MIT) or [Apache-2.0](LICENSE-APACHE), at your option. Notices
|
||||
|
||||
@@ -28,10 +28,10 @@ pressure) is a degree of freedom of the existing DOF framework, not a separate s
|
||||
|---|---|---|
|
||||
| M0 Foundation | Workspace, quality gates, FE model, command engine with rollback and panic guard, CLI, geometry boundary on SolidCraft | done |
|
||||
| M1 Geometry in and surface preparation | Open `.solidcraft` designs with persistent face names, assemblies placed (done); face-tagged 3MF (done); test corpus, `cargo xtask corpus` (done); exact predicates (done); quality metrics and certified validity gate (done); weld, closed/manifold/orientation and self-intersection checks, feature edges (`fieldcraft-mesh::surface`, `mesh.surface.check`, done) | in progress |
|
||||
| M2 Tet meshing and size field | Size field (global, per face and edge seeds, curvature and proximity; the `fieldcraft_mesh::size::SizeField` trait and edge-division helpers are in); Bowyer–Watson Delaunay (exact, symbolic perturbation, verified; `fieldcraft-mesh::delaunay`, done); robust CDT boundary recovery (Diazzi et al. 2023: implicit LNC Steiner points on segments, gift-wrapping facet recovery, inside/outside labelling, B-rep face tags on boundary tet faces, flip repair of rounding (§5.1) checked by the validity gate; `fieldcraft-mesh::cdt` and `mesh.tet.generate`, done: all 20 valid corpus parts); quality stage (done: `fieldcraft-mesh::tet` — curvature-graded size field, edge-collapse coarsening, constrained Delaunay refinement with boundary points on the B-rep faces and curves, ODT smoothing, Klingner–Shewchuk improvement, tet4 and tet10 with mid-side nodes on the B-rep, quality report; one validity criterion shared by the gate and both solvers; the filleted-bracket fillet stress converges, tests/oracle); mesh verify per set | in progress |
|
||||
| M2 Tet meshing and size field | Size field (global, curvature and proximity; edge seeds done: `mesh.seed.edge` on persistent design edge names (`<face>|<face>`) with a count or size, geometric bias and an exact, min or free constraint, shown as ticks and under Mesh › Seeds, honoured by the hex sweep, extrude, revolve, mapped, blocks and cells meshers through interval assignment (conflicting exact seeds named) and by the tet mesher, which divides the edge at the seed's nodes and grades its size field from them; per-face seeds to do; the `fieldcraft_mesh::size::SizeField` trait and edge-division helpers are in); Bowyer–Watson Delaunay (exact, symbolic perturbation, verified; `fieldcraft-mesh::delaunay`, done); robust CDT boundary recovery (Diazzi et al. 2023: implicit LNC Steiner points on segments, gift-wrapping facet recovery, inside/outside labelling, B-rep face tags on boundary tet faces, flip repair of rounding (§5.1) checked by the validity gate; `fieldcraft-mesh::cdt` and `mesh.tet.generate`, done: all 20 valid corpus parts); quality stage (done: `fieldcraft-mesh::tet` — curvature-graded size field, edge-collapse coarsening, constrained Delaunay refinement with boundary points on the B-rep faces and curves, ODT smoothing, Klingner–Shewchuk improvement, tet4 and tet10 with mid-side nodes on the B-rep, quality report; one validity criterion shared by the gate and both solvers; the filleted-bracket fillet stress converges, tests/oracle); mesh verify per set | in progress |
|
||||
| M3 First deck | Sets and surfaces bound to SolidCraft face, edge, vertex and body names, resolved after meshing; materials (isotropic and orthotropic elastic, density) with a unit-system label and consistency check; sections (solid, shell, beam profiles) assigned by set; element formulation per region mapped to each solver; BCs (fixed, displacement, symmetry); loads (force and moment on reference points, pressure, gravity); reference points with kinematic and distributing coupling; steps (linear static, frequency) with explicit per-step load and BC tables and output presets; `model.check` naming every missing or bad item; `model.*` and `mesh.tag` commands (model definition: done); writers for Abaqus input (done: `deck.write`), Nastran SOL 101/103 (done: `deck.write`) and LS-DYNA implicit (done); the `.fieldcraft` file (text definition, binary mesh, geometry references reopened on load, journal; atomic saves, autosave and recovery; undo/redo on the journal: done) | in progress |
|
||||
| M4 Own solver and first results | Element library per docs/elements.md (1D and 2D first); Linear static and modal solver (tet4/10, wedge6, hex8, hex20; sparse direct, Lanczos), verified against analytic solutions (solver: done — `fieldcraft-fem` kernels, `fieldcraft-solver` with nested dissection, sparse Cholesky and block Lanczos, `solve.static`/`solve.frequency`/`solve.probe`, patch, cantilever, Lamé, Kirsch and beam-frequency tests; reference points with kinematic and distributing couplings and moments by master–slave constraint elimination, verified by rigid motion, clamping, Saint-Venant tension, bending and tube torsion; 1D elements I: rod2/rod3 trusses, point masses, rotary inertia, springs and dashpots in both solvers and all three decks, verified by the method of joints, the three-bar truss, spring–mass, two-mass chain and torsional pendulum frequencies, and damped decay; 2D elements: plane stress, plane strain and axisymmetric tri3, tri6, quad4 (incompatible modes QM6), quad8 with two degrees of freedom per node, centrifugal loads, `mesh.planar` 2D meshes of polygons and planar faces, verified by patch tests, Kirsch, Lamé (plane strain and axisymmetric), rotating discs and cylinders, and a plane stress cantilever; deck mapping to Abaqus CPS/CPE/CAX, Nastran membranes, LS-DYNA ELFORM 12/13); shells and beams (done: quad4 MITC4 and tri3 MITC3 flat shells with a Hughes–Brezzi drilling rotation, two-node Timoshenko beams with profile properties and orientations, six degrees of freedom at shell and beam nodes shared with solids and trusses, section forces and surface stresses, verified by shell patch tests, Navier's plate, cantilever and portal-frame beams, and the Scordelis–Lo and pinched-cylinder benchmarks); results display (done: `results.*` commands, deformed shape to scale, banded contours of displacement, von Mises, principal and component stresses with a legend, mode shapes with their frequencies and animation, probing a node by clicking it, reaction force and moment sums per set, stale results marked after an edit; explicit steps: field frames by slider or animation with contours per frame, energy histories plotted) | started |
|
||||
| M5 Structured hex | 2D quad meshing of faces (`fieldcraft-mesh::quad`: transfinite mapped meshes, free all-quad meshes of polygons with holes on prescribed boundary nodes, exact planar quad validity, shared `SizeField` and even edge divisions; done for planar faces); mapped hex of six-sided regions (trivariate TFI, curved faces) and sweep meshing (multi-level extrusions with imprinted cross-sections, revolutions, one-to-one sweeps through linking faces; interval assignment, hex8/hex20 on the geometry, B-rep face tags, `mesh.hex.generate`/`sweep`/`mapped`: done, 16 of 21 corpus parts all-hex); conforming interfaces between cells (done: `mesh.hex.blocks` meshes a part split with SolidCraft's Split Body into mapped blocks as one conforming mesh — composite faces for seams and tangent faces, interval assignment over all cells, shared faces meshed once, grading off holes and fillets, free-internal-face check; the filleted bracket in 30 cells, hex20 within 0.1 % of a fine tet10 tip deflection); sweepable cells in a conforming mesh and tet–hex transition; automatic decomposition into sweepable and mappable regions, proposed as SolidCraft splits | started |
|
||||
| M5 Structured hex | 2D quad meshing of faces (`fieldcraft-mesh::quad`: transfinite mapped meshes, free all-quad meshes of polygons with holes on prescribed boundary nodes, exact planar quad validity, shared `SizeField` and even edge divisions; done for planar faces); mapped hex of six-sided regions (trivariate TFI, curved faces) and sweep meshing (multi-level extrusions with imprinted cross-sections, revolutions, one-to-one sweeps through linking faces; interval assignment, hex8/hex20 on the geometry, B-rep face tags, `mesh.hex.generate`/`sweep`/`mapped`: done, 16 of 21 corpus parts all-hex); conforming interfaces between cells (done: `mesh.hex.blocks` meshes a part split with SolidCraft's Split Body into mapped blocks as one conforming mesh — composite faces for seams and tangent faces, interval assignment over all cells, shared faces meshed once, grading off holes and fillets, free-internal-face check; the filleted bracket in 30 cells, hex20 within 0.1 % of a fine tet10 tip deflection); partitions inside FieldCraft (done: datum planes and axes, `geometry.partition` cuts the open design by a datum plane, kept in the model and replayed when the design opens, the two faces of each cut paired by name); cells meshed each with its own method into one mesh (done: `mesh.cells` — hex where a method fits, else tet; matching interfaces merged node for node, others, such as hex next to tet, tied by dual mortar, verified by a tied hex–tet bar in tension to 1e-6); meshing half a symmetric part and mirroring it (done: `mesh.mirror` reflects hex8/hex20/tet4/tet10/wedge6 across a datum plane, right-handed, nodes on the plane merged, tags carried to the image half; a mirrored half bar equals the whole bar's mesh and bending deflection to 1e-12; samples `crank-arm` and `crank-mirror`: one datum, the half extruded in automatic blocks and mirrored, scaled Jacobian ≥ 0.37; or solving the half: `model.boundary_condition.symmetry` on a datum plane, a half bar with half the load bends as the whole to 1e-11); three-sided sweep regions mapped as triangle primitives (done: midpoint subdivision, dominance constraints in interval assignment); automatic blocks of extruded cross-sections (done: `hex::decompose` — holes separated, O-grids, cuts from concave corners and fillets chosen by block quality, kept only when no worse than the free mesh; nothing added to the model); pyramid transitions; automatic decomposition of 3D parts into sweepable and mappable regions | started |
|
||||
| M6 Automatic hex | Octree/grid all-hex for any part (first version: done — `fieldcraft-mesh::octree`, `mesh.hex.octree`: 3-refinement grid with conforming templates refined by curvature, thickness and narrow faces, a core cleared to a manifold boundary, feature map onto it, padding and a pillow per patch capturing every sharp curve, foldover-free fitting, certified validity, B-rep face tags; the corpus hex column and the filleted-bracket oracle case; next: transitions for concave refined regions so thin and curved parts stop over-refining); hex-dominant by tet recombination; polycube for blocky parts; layers through thin walls; mesh editing and orphan-mesh import | started |
|
||||
| M7 Assemblies, contact and friction | Needs M15. Part instances from SolidCraft occurrences; tie between non-matching meshes (mortar: done — `interaction.tie`, dual mortar constraints in the implicit analyses, Abaqus `*TIE` and LS-DYNA tied contact, the tie patch test); implicit contact: surface-to-surface mortar and node-to-surface, penalty and augmented Lagrange, self-contact, automatic pair detection (mortar contact pairs with Coulomb friction in nonlinear static steps: done — segment-to-segment mortar with the consistent tangent by automatic differentiation of the segmentation, augmented Lagrangian with Uzawa updates to a gap tolerance, semismooth active set with a chattering cutback, small sliding without nonlinear geometry and finite sliding with it, overclosure adjusted or refused, Coulomb friction (stick/slip return map, static and kinetic coefficients, symmetrised tangent), pressure, gap, status, shear and slip output; verified by the contact patch test, Hertz cylinder and sphere, Newton's quadratic rate and sliding blocks; the linear analyses refuse contact by name); friction: Coulomb with stick–slip, static/kinetic, anisotropic, pressure-, rate- and temperature-dependent coefficients; contact output (pressure, slip, status); thermal contact conductance and frictional heating; wear (Archard); bolt pretension, connectors with behaviour (elastic, damped, stops, locks); amplitudes, multiple steps, restart; nonlinear steps in all three decks. Verified by Hertz (sphere and cylinder), the Cattaneo–Mindlin partial-slip problem, the sliding block, NAFEMS contact benchmarks | started |
|
||||
| M8 Materials, explicit, shells, composites | Plasticity, hyperelasticity, damage data per solver; explicit dynamics decks (Abaqus/Explicit, LS-DYNA); midsurface shells; composite layups and material orientations, continuum shells on swept hex; hybrid (mixed u–p) hex8/hex20/tet10 for nearly incompressible materials (done); heat transfer (solids done: steady and θ-method transient conduction with flux, convection and sources, thermal strain in static steps (solids and 2D) and explicit dynamics (with plasticity), coupled temperature–displacement, `solve.heat`; deck output, 2D/shell/beam conduction planned) | started |
|
||||
@@ -52,7 +52,7 @@ pressure) is a degree of freedom of the existing DOF framework, not a separate s
|
||||
| M23 Wave propagation and ultrasound | Elastic, acoustic and coupled waves from the explicit solver's 1D bar today to guided and ultrasonic waves, by two methods. Finite differences first, for fast 2D (then 3D) ultrasound on regular grids: staggered-grid velocity–stress FDTD (Virieux) and the elastodynamic finite integration technique for solids, the rotated staggered grid for anisotropic media, a k-space pseudospectral scheme for weakly heterogeneous tissue and water, all on grids voxelised from the face-tagged geometry by the LBM's exact voxeliser, with heterogeneous, layered and fluid–solid media, CPML boundaries, threads and the GPU backend; staircased curved boundaries scatter spuriously, so the FD grid is checked against the finite elements on curved parts. Finite elements for curved geometry and coupling with structures: spectral elements (high-order Gauss–Lobatto–Legendre hexes with diagonal mass) on the hex meshes, and a mesh check in elements per wavelength with the dispersion error it implies; absorbing boundaries (convolutional PML, absorbing layers with increasing damping) and infinite media; tone-burst sources (Hann-windowed cycles), point, line and surface excitation, and piezoelectric transducers (M19); anisotropic media (composites, crystals) and viscoelastic, power-law-in-frequency attenuation; fluid–solid interfaces and fluid-loaded plates; ultrasound in water and tissue, nonlinear acoustics (Westervelt, KZK) for focused ultrasound. Guided waves: dispersion curves by semi-analytical finite elements (SAFE) for plates, pipes, rails and layered and anisotropic laminates — Lamb, Rayleigh, Love and SH modes — with phase and group velocities and mode shapes; mode-selective excitation. Output: A-scans and B-scans at sensors, wavefield snapshots, 2D FFT (frequency–wavenumber) for mode identification, and time–frequency diagrams of any signal — short-time Fourier spectrograms, continuous wavelet transforms (Morlet), reassigned spectrograms and smoothed pseudo Wigner–Ville — with the SAFE or Rayleigh–Lamb group-velocity curves overlaid as arrival times, and group velocities extracted from the ridges. GPU paths (M12's backend) for long runs. Verified by Lamb's problem (point load on a half-space), Rayleigh-wave speed, Rayleigh–Lamb dispersion, Love waves in a layer over a half-space, reflection and transmission at interfaces, and published guided-wave measurements | planned |
|
||||
| Continuous: verification and validation | Every capability checked against theory (closed forms), experiments (published measurements) and published benchmarks (NAFEMS, vendor benchmark and verification manuals such as Abaqus's), each case our own model in `tests/oracle/` with its cited reference and tolerance; `cargo xtask oracle` runs them and writes docs/oracle.md; once a case matches, our result is frozen as a fixture so fidelity cannot regress (docs/verification.md). Runner, fixtures and CI job: done; 26 theory cases (patch tests of every solid element, cantilevers, Lamé in 3D, plane strain and axisymmetric, Kirsch in 3D and plane stress, rotating disc and cylinder, beam frequencies, couplings, explicit waves, impact and J2 plasticity, CDT invariants), 9 published benchmarks (MacNeal–Harder solid tests, Scordelis–Lo with solids, NAFEMS LE1 in 3D and 2D, LE10, FV32) and 9 pending cases with citations (shells, thermal, static plasticity, Taylor bar, CFD); `mesh.block` mapped blocks and 2D patches build their meshes | started |
|
||||
| Continuous: performance | CPU first, deterministic: results never depend on the thread count (fixed partitions, sums in a fixed order; checked by hashing results on 1, 2 and 7 threads). Supernodal left-looking Cholesky (11–15× faster than the column solver on one thread), parallel element matrices, stresses and Lanczos products, explicit element updates and LBM cell blocks on rayon threads (done — `fieldcraft-parallel`, `threads` on the solve commands, `FIELDCRAFT_THREADS`); parallel forward/back substitution and explicit tet4 assembly; GPU paths later, within a stated tolerance of the CPU | started |
|
||||
| Continuous: desktop and agents | Desktop app (viewport, model tree, commands, control channel, the open design drawn, `ui.capture` of the whole window offscreen: done; toolbar of every capability from the catalogue, ready or coming soon with its milestone, icons drawn with VectorCraft, docs/features.md: done; the Craft-family shell — title bar, workspaces and ribbon drop-downs, browser, context panel, command search, journal timeline, light and dark themes — native file pickers with background opening, drag and drop and recent files, samples and one-click Solve, and an examples gallery of ready-to-solve samples, each checked by a test (docs/examples.md): done; MCP server over stdio, headless or bridged to the app, with read and write roots, docs/mcp.md: done; caps labels in Inter SemiBold; the README's analysis video recorded through MCP by `tools/demo-video`: done; support, load, reference-point and coupling symbols in the viewport and headless renders, with their browser toggles: done; selection by picking in the viewport — geometry faces, edges, vertices and bodies, mesh nodes, element faces and elements, box selection, hover, a Target row in command forms, `ui.select`/`ui.selection` and MCP `select`: done; a camera parameter for screenshots, a ribbon that follows the command being run: in progress; the browser build — the same app in a web page with browser file pickers, downloads, drops and autosave to browser storage, deployed to GitHub Pages from each release, docs/web.md: done), command schema as the public API | started |
|
||||
| Continuous: desktop and agents | Desktop app (viewport, model tree, commands, control channel, the open design drawn, `ui.capture` of the whole window offscreen: done; toolbar of every capability from the catalogue, ready or coming soon with its milestone, icons drawn with VectorCraft, docs/features.md: done; the Craft-family shell — title bar, workspaces and ribbon drop-downs, browser, context panel, command search, journal timeline, light and dark themes — native file pickers with background opening, drag and drop and recent files, samples and one-click Solve, and an examples gallery of ready-to-solve samples, each checked by a test (docs/examples.md): done; MCP server over stdio, headless or bridged to the app, with read and write roots, docs/mcp.md: done; caps labels in Inter SemiBold; the README's analysis video recorded through MCP by `tools/demo-video`: done; support, load, reference-point and coupling symbols in the viewport and headless renders, with their browser toggles: done; symbols as wireframes, one mark per constrained degree of freedom, a constant size on screen with a size setting, highlighted with their selected definition, concentrated loads drawn over the part: done; selection by picking in the viewport — geometry faces, edges, vertices and bodies, mesh nodes, element faces and elements, box selection, hover, a Target row in command forms, `ui.select`/`ui.selection` and MCP `select`: done; a camera parameter for screenshots, a ribbon that follows the command being run: in progress; the browser build — the same app in a web page with browser file pickers, downloads, drops and autosave to browser storage, deployed to GitHub Pages from each release, docs/web.md: done; in-app updates — a daily check of GitHub Releases, Help › Check for Updates and Reinstall, downloads verified against the release key's signature of SHA256SUMS.txt and swapped in after closing, `app.update.check`, `fieldcraft-cli update`, Reload to update in the browser, docs/updates.md: done), command schema as the public API | started |
|
||||
|
||||
## Next
|
||||
|
||||
|
||||
@@ -12,4 +12,8 @@ workspace = true
|
||||
fieldcraft-engine = { workspace = true }
|
||||
fieldcraft-io = { workspace = true }
|
||||
fieldcraft-mcp = { workspace = true }
|
||||
fieldcraft-update = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
fieldcraft-update = { workspace = true, features = ["mock"] }
|
||||
@@ -0,0 +1,80 @@
|
||||
//! `fieldcraft-cli crashes`: the crash reports the desktop app wrote on this computer
|
||||
//! (docs/crash-reports.md): list them, show one, replay one, delete them.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use fieldcraft_engine::crash;
|
||||
use serde_json::json;
|
||||
|
||||
pub const USAGE: &str = "usage: fieldcraft-cli crashes [list [--json] | show <id> | replay <id> | dir | clear [<id>]]";
|
||||
|
||||
pub fn run(args: &[String]) -> Result<(), String> {
|
||||
let dir = crash::default_dir().ok_or("no crash folder on this system (set FIELDCRAFT_CRASH_DIR)")?;
|
||||
let id = || args.get(1).map(String::as_str).ok_or_else(|| USAGE.to_string());
|
||||
match args.first().map(String::as_str) {
|
||||
None | Some("list") => {
|
||||
let reports = crash::list(&dir);
|
||||
if args.iter().any(|a| a == "--json") {
|
||||
return print_json(&json!({ "dir": dir.to_string_lossy(), "reports": reports }));
|
||||
}
|
||||
println!("crash reports in {}", dir.display());
|
||||
if reports.is_empty() {
|
||||
println!(" (none)");
|
||||
}
|
||||
for r in reports {
|
||||
let times = if r.count > 1 { format!(" ×{}", r.count) } else { String::new() };
|
||||
let cmd = r.command.map(|c| format!(" in {c}")).unwrap_or_default();
|
||||
let replay = if r.replayable { " [replayable]" } else { "" };
|
||||
println!(" {} {}{times}{cmd} v{}{replay}\n {}", r.id, r.kind, r.version, r.message);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Some("show") => print_json(&crash::read(&dir, id()?)?),
|
||||
Some("replay") => replay(&dir, id()?),
|
||||
Some("dir") => {
|
||||
println!("{}", dir.display());
|
||||
Ok(())
|
||||
}
|
||||
Some("clear") => {
|
||||
println!("deleted {} report(s)", crash::clear(&dir, args.get(1).map(String::as_str)));
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(USAGE.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn print_json(v: &serde_json::Value) -> Result<(), String> {
|
||||
println!("{}", serde_json::to_string_pretty(v).map_err(|e| e.to_string())?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Run a report's commands on its model and say whether the crash happens again. Files the
|
||||
/// commands write go to a scratch folder, never over the user's files.
|
||||
fn replay(dir: &Path, id: &str) -> Result<(), String> {
|
||||
let report = crash::read(dir, id)?;
|
||||
let scratch = std::env::temp_dir().join(format!("fieldcraft-replay-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&scratch).map_err(|e| format!("{}: {e}", scratch.display()))?;
|
||||
if report["kind"] == "unclean_exit" {
|
||||
println!("this crash ended the app without a report: if this process ends abruptly, it reproduced");
|
||||
}
|
||||
println!("replaying on {}", report["model_path"].as_str().unwrap_or("a new model"));
|
||||
let r = crash::replay(&report, &scratch);
|
||||
let _ = std::fs::remove_dir_all(&scratch);
|
||||
let r = r?;
|
||||
for (i, (cmd, outcome)) in r.steps.iter().enumerate() {
|
||||
match outcome {
|
||||
Ok(()) => println!(" {:>3}. {cmd}: ok", i + 1),
|
||||
Err(e) => println!(" {:>3}. {cmd}: {e}", i + 1),
|
||||
}
|
||||
}
|
||||
let said = |k: &str| report[k].as_str().unwrap_or_default().to_string();
|
||||
if r.reproduced {
|
||||
println!("reproduced: the same internal error ({}) at {}", said("message"), said("location"));
|
||||
} else if let Some((l, m)) = r.panics.first() {
|
||||
println!("an internal error happened, but not the reported one: {m} at {l}");
|
||||
println!("(the report says: {} at {})", said("message"), said("location"));
|
||||
} else {
|
||||
println!("did not reproduce: no internal error (fixed, or it depends on something the replay does not have)");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -2,10 +2,15 @@
|
||||
//! fieldcraft-cli run <script.json>
|
||||
//! fieldcraft-cli features
|
||||
//! fieldcraft-cli mcp [--connect ADDR | --headless] [--automation-read-root DIR] [--automation-write-root DIR]
|
||||
//! fieldcraft-cli crashes [list [--json] | show <id> | replay <id> | dir | clear [<id>]]
|
||||
//! fieldcraft-cli update --check | --install
|
||||
//! fieldcraft-cli --version
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
mod crashes;
|
||||
mod update;
|
||||
|
||||
use std::path::Path;
|
||||
use std::process::ExitCode;
|
||||
|
||||
@@ -28,6 +33,14 @@ usage:
|
||||
--automation-read-root DIR files may be read only inside DIR
|
||||
--automation-write-root DIR files may be written only inside DIR (with either root,
|
||||
the access a root left out is not granted)
|
||||
fieldcraft-cli crashes [list|show <id>|replay <id>|dir|clear [<id>]]
|
||||
the crash reports the desktop app wrote on this
|
||||
computer (docs/crash-reports.md): list them (--json),
|
||||
show one, replay one (does the crash happen again?),
|
||||
print their folder, delete them
|
||||
fieldcraft-cli update --check is a newer FieldCraft published? (app.update.check; JSON)
|
||||
fieldcraft-cli update --install download the latest release, verify its signature and
|
||||
checksum, and install it over this copy (docs/updates.md)
|
||||
fieldcraft-cli --version print the version
|
||||
";
|
||||
|
||||
@@ -52,6 +65,8 @@ fn main() -> ExitCode {
|
||||
Ok(())
|
||||
}
|
||||
Some("mcp") => mcp(args.get(1..).unwrap_or(&[])),
|
||||
Some("crashes") => crashes::run(args.get(1..).unwrap_or(&[])),
|
||||
Some("update") => update::run(args.get(1..).unwrap_or(&[])),
|
||||
Some("run") => args.get(1).ok_or_else(|| format!("run needs a script\n\n{USAGE}")).and_then(|p| run(p)),
|
||||
Some("-V" | "--version") => {
|
||||
println!("fieldcraft-cli {}", env!("CARGO_PKG_VERSION"));
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
//! `fieldcraft-cli update --check | --install` (docs/updates.md): the same check as the app's
|
||||
//! Help › Check for Updates (`app.update.check`), and installing the latest release over this
|
||||
//! copy of the CLI's install, verified against the release key first. `FIELDCRAFT_UPDATE_HOST`
|
||||
//! points both at a local test server.
|
||||
|
||||
use fieldcraft_engine::Session;
|
||||
use fieldcraft_update::install::{self, Finish};
|
||||
use fieldcraft_update::net::Client;
|
||||
use fieldcraft_update::stage::{self, Options};
|
||||
use serde_json::json;
|
||||
|
||||
pub const USAGE: &str = "usage: fieldcraft-cli update --check | --install";
|
||||
|
||||
pub fn run(args: &[String]) -> Result<(), String> {
|
||||
match args.iter().map(String::as_str).collect::<Vec<_>>().as_slice() {
|
||||
["--check"] => check(),
|
||||
["--install"] => install(),
|
||||
_ => Err(USAGE.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn check() -> Result<(), String> {
|
||||
fieldcraft_engine::enable_update_checks(true);
|
||||
let report = Session::default().execute("app.update.check", &json!({})).map_err(|e| e.to_string())?;
|
||||
println!("{}", serde_json::to_string_pretty(&report).map_err(|e| e.to_string())?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn install() -> Result<(), String> {
|
||||
let client = Client::from_env();
|
||||
let check = client.check().map_err(|e| e.to_string())?;
|
||||
if !check.newer() {
|
||||
println!("FieldCraft {} is up to date (the latest release is {}).", check.current, check.latest.version);
|
||||
return Ok(());
|
||||
}
|
||||
let here = install::here();
|
||||
let downloads = fieldcraft_io::recovery::data_dir().map(|d| d.join("updates")).unwrap_or_else(|| std::env::temp_dir().join("fieldcraft-updates"));
|
||||
eprintln!("Downloading FieldCraft {} for {}…", check.latest.version, here.describe());
|
||||
let progress = |done: u64, total: u64| {
|
||||
if total > 0 && done == total {
|
||||
eprintln!("Downloaded {} MB; verifying…", total / (1024 * 1024));
|
||||
}
|
||||
};
|
||||
let options = Options { key: fieldcraft_update::PUBLIC_KEY, downloads: &downloads, arch: std::env::consts::ARCH, progress: &progress };
|
||||
let staged = stage::stage(&client, &check.latest, &here, &options).map_err(|e| e.to_string())?;
|
||||
match install::plan(&staged, false).map_err(|e| e.to_string())? {
|
||||
Finish::Swap(plan) => {
|
||||
stage::apply(&plan).map_err(|e| e.to_string())?;
|
||||
println!("Installed FieldCraft {} ({}). A running FieldCraft app uses it from its next start.", staged.version, here.describe());
|
||||
}
|
||||
Finish::Package { file, command } => {
|
||||
println!("Downloaded and verified {}.\nInstall it with the system's package manager:\n {command}", file.display());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
//! `fieldcraft-cli crashes` on a crash folder of its own (`FIELDCRAFT_CRASH_DIR`).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
use fieldcraft_engine::Session;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
const ID: &str = "20261014-101500-00000000deadbeef";
|
||||
|
||||
/// A replayable report: a model with two nodes and a replay that adds a third.
|
||||
fn folder() -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("fieldcraft-cli-crashes-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
let r = d.join(ID);
|
||||
std::fs::create_dir_all(&r).unwrap();
|
||||
let mut s = Session::default();
|
||||
for l in 1..=2 {
|
||||
s.execute("mesh.node.add", &json!({"label": l, "xyz": [l, 0, 0]})).unwrap();
|
||||
}
|
||||
std::fs::write(r.join("model.fieldcraft"), s.file_bytes(None).unwrap()).unwrap();
|
||||
let replay = json!({"commands": [
|
||||
{"command": "mesh.node.add", "params": {"label": 3, "xyz": [3, 0, 0]}},
|
||||
{"command": "file.save", "params": {"path": d.join("overwritten.fieldcraft")}},
|
||||
]});
|
||||
std::fs::write(r.join("replay.json"), replay.to_string()).unwrap();
|
||||
let report = json!({
|
||||
"format": "fieldcraft-crash/1", "id": ID, "kind": "unclean_exit", "signature": "00000000deadbeef", "count": 2,
|
||||
"first_seen": "2026-10-14T10:15:00Z", "message": "FieldCraft ended without a clean exit while running `mesh.node.add`",
|
||||
"location": "unclean exit in mesh.node.add", "command": {"command": "mesh.node.add", "params": {}},
|
||||
"app": {"version": "9.9.9"}, "backtrace": [],
|
||||
});
|
||||
std::fs::write(r.join("report.json"), report.to_string()).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
fn cli(dir: &Path, args: &[&str]) -> (String, bool) {
|
||||
let out = Command::new(env!("CARGO_BIN_EXE_fieldcraft-cli")).args(args).env("FIELDCRAFT_CRASH_DIR", dir).output().unwrap();
|
||||
(format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)), out.status.success())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crashes_list_show_replay_and_clear() {
|
||||
let d = folder();
|
||||
let (out, ok) = cli(&d, &["crashes"]);
|
||||
assert!(ok, "{out}");
|
||||
assert!(out.contains(ID) && out.contains("unclean_exit ×2 in mesh.node.add") && out.contains("[replayable]"), "{out}");
|
||||
let (out, ok) = cli(&d, &["crashes", "list", "--json"]);
|
||||
assert!(ok);
|
||||
let v: Value = serde_json::from_str(&out).unwrap();
|
||||
assert_eq!(v["reports"][0]["id"], ID);
|
||||
let (out, ok) = cli(&d, &["crashes", "show", ID]);
|
||||
assert!(ok);
|
||||
let v: Value = serde_json::from_str(&out).unwrap();
|
||||
assert!(v["model_path"].as_str().unwrap().ends_with("model.fieldcraft"));
|
||||
let (out, ok) = cli(&d, &["crashes", "replay", ID]);
|
||||
assert!(ok, "{out}");
|
||||
assert!(out.contains("1. mesh.node.add: ok"), "{out}");
|
||||
// A command that writes a file is refused outside the scratch folder: the replay never
|
||||
// writes over the user's files.
|
||||
assert!(out.contains("2. file.save: ") && out.contains("outside the write root"), "{out}");
|
||||
assert!(!d.join("overwritten.fieldcraft").exists());
|
||||
assert!(out.contains("did not reproduce"), "{out}");
|
||||
let (out, ok) = cli(&d, &["crashes", "show", "../etc"]);
|
||||
assert!(!ok && out.contains("no crash report"), "{out}");
|
||||
let (out, ok) = cli(&d, &["crashes", "dir"]);
|
||||
assert!(ok && out.trim() == d.to_string_lossy(), "{out}");
|
||||
let (out, ok) = cli(&d, &["crashes", "clear"]);
|
||||
assert!(ok && out.contains("deleted 1 report(s)"), "{out}");
|
||||
let (out, _) = cli(&d, &["crashes"]);
|
||||
assert!(out.contains("(none)"), "{out}");
|
||||
let (out, ok) = cli(&d, &["crashes", "nope"]);
|
||||
assert!(!ok && out.contains("usage"), "{out}");
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
//! `fieldcraft-cli update --check` against a local release server (FIELDCRAFT_UPDATE_HOST).
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
use fieldcraft_update::mock::Server;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn cli(host: &str, args: &[&str]) -> std::process::Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_fieldcraft-cli")).args(args).env("FIELDCRAFT_UPDATE_HOST", host).output().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_check_reports_the_latest_release() {
|
||||
let server = Server::start().unwrap();
|
||||
server.release("latest", &json!({"tag_name": "v99.0.0", "html_url": "https://github.com/jyviko/fieldcraft/releases/tag/v99.0.0", "assets": []}));
|
||||
let out = cli(&server.url(), &["update", "--check"]);
|
||||
assert!(out.status.success(), "{out:?}");
|
||||
let report: Value = serde_json::from_slice(&out.stdout).unwrap();
|
||||
assert_eq!(report["current"], env!("CARGO_PKG_VERSION"));
|
||||
assert_eq!((report["latest"].as_str(), report["newer"].as_bool(), report["signed"].as_bool()), (Some("99.0.0"), Some(true), Some(false)));
|
||||
// A test build is not a release package: it checks but would not install.
|
||||
assert_eq!(report["asset"], Value::Null);
|
||||
assert_eq!(server.requests(), 1);
|
||||
|
||||
// The same version: not newer, and --install has nothing to do.
|
||||
server.release("latest", &json!({"tag_name": format!("v{}", env!("CARGO_PKG_VERSION")), "assets": []}));
|
||||
let out = cli(&server.url(), &["update", "--check"]);
|
||||
assert_eq!(serde_json::from_slice::<Value>(&out.stdout).unwrap()["newer"], false);
|
||||
let out = cli(&server.url(), &["update", "--install"]);
|
||||
assert!(out.status.success() && String::from_utf8_lossy(&out.stdout).contains("is up to date"), "{out:?}");
|
||||
|
||||
// Unreachable: an error, not a crash.
|
||||
let out = cli("http://127.0.0.1:1", &["update", "--check"]);
|
||||
assert!(!out.status.success() && String::from_utf8_lossy(&out.stderr).contains("could not reach"), "{out:?}");
|
||||
assert!(!cli(&server.url(), &["update"]).status.success());
|
||||
}
|
||||
@@ -29,6 +29,6 @@ rfd = { workspace = true, features = ["file-handle-inner"] }
|
||||
wasm-bindgen = "0.2"
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "0.3"
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "DomTokenList", "CssStyleDeclaration", "Event", "EventTarget", "BeforeUnloadEvent", "Storage"] }
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "DomTokenList", "CssStyleDeclaration", "Event", "EventTarget", "BeforeUnloadEvent", "Storage", "Crypto", "Headers", "Request", "RequestInit", "RequestCache", "Response"] }
|
||||
# Autosaves kept in the browser's local storage, which holds text.
|
||||
base64 = "0.22"
|
||||
@@ -0,0 +1,75 @@
|
||||
//! A new deployment of the web app: every half hour the page's own address is fetched past the browser's cache, and when it loads another build
|
||||
//! of the app than the one running (Trunk names each build's files by their content hash), the
|
||||
//! status bar offers "Reload to update" (docs/updates.md). Reloading asks first when the model
|
||||
//! has unsaved changes, as closing the page does.
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use wasm_bindgen::JsCast as _;
|
||||
|
||||
/// How often the page looks for a new deployment (seconds).
|
||||
pub const INTERVAL: f64 = 30.0 * 60.0;
|
||||
|
||||
/// Watches for a new deployment.
|
||||
pub struct Watch {
|
||||
/// The build this page runs.
|
||||
running: Option<String>,
|
||||
/// A fetch found another build.
|
||||
found: Rc<Cell<bool>>,
|
||||
/// App time of the last look.
|
||||
pub looked_at: f64,
|
||||
}
|
||||
|
||||
impl Watch {
|
||||
pub fn start() -> Watch {
|
||||
let html = web_sys::window().and_then(|w| w.document()).and_then(|d| d.document_element()).map(|e| e.outer_html()).unwrap_or_default();
|
||||
let running = crate::build_in_page(&html).map(str::to_string);
|
||||
if running.is_none() {
|
||||
log::info!("deploy: no hashed build in the page (a development server?); not watching");
|
||||
}
|
||||
Watch { running, found: Rc::default(), looked_at: 0.0 }
|
||||
}
|
||||
|
||||
/// Whether a newer deployment was found.
|
||||
pub fn found(&self) -> bool {
|
||||
self.found.get()
|
||||
}
|
||||
|
||||
/// Fetch the page again and compare its build with the running one.
|
||||
pub fn look(&self) {
|
||||
let (Some(running), Some(window)) = (self.running.clone(), web_sys::window()) else { return };
|
||||
if self.found.get() {
|
||||
return;
|
||||
}
|
||||
let url = window.location().pathname().unwrap_or_else(|_| "./".into());
|
||||
let init = web_sys::RequestInit::new();
|
||||
init.set_cache(web_sys::RequestCache::NoStore);
|
||||
let promise = window.fetch_with_str_and_init(&url, &init);
|
||||
let found = self.found.clone();
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
let text = async {
|
||||
let response: web_sys::Response = wasm_bindgen_futures::JsFuture::from(promise).await.ok()?.dyn_into().ok()?;
|
||||
if !response.ok() {
|
||||
return None;
|
||||
}
|
||||
wasm_bindgen_futures::JsFuture::from(response.text().ok()?).await.ok()?.as_string()
|
||||
};
|
||||
// Offline or refused: look again next time.
|
||||
if let Some(html) = text.await
|
||||
&& let Some(deployed) = crate::build_in_page(&html)
|
||||
&& deployed != running
|
||||
{
|
||||
log::info!("deploy: {deployed} is deployed (running {running})");
|
||||
found.set(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Reload the page (the new deployment loads).
|
||||
pub fn reload() {
|
||||
if let Some(w) = web_sys::window() {
|
||||
let _ = w.location().reload();
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,8 @@
|
||||
//! - files live in the page ([`fieldcraft_io::fs`] keeps them in memory): File › Open and drops
|
||||
//! read the computer's files into it; Save, Save As and Write Deck hand the written file out as
|
||||
//! a download;
|
||||
//! - autosaves for recovery are kept in the browser's local storage ([`storage`]);
|
||||
//! - autosaves for recovery and the preferences are kept in the browser's local storage
|
||||
//! ([`storage`], [`usage`]), and anonymous usage (when agreed) goes out with `fetch`;
|
||||
//! - no control channel (a page can't listen on a socket);
|
||||
//! - background jobs (meshing, solving) run on the page's one thread once the window has shown
|
||||
//! that they run.
|
||||
@@ -17,9 +18,13 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod deploy;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod storage;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod usage;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod web;
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
@@ -42,6 +47,25 @@ fn sample_in_query(query: &str) -> Option<String> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The build of the app a page loads: the content-hashed name Trunk gives its WebAssembly
|
||||
/// (`fieldcraft-web-<hash>_bg.wasm`). A new deployment loads another one.
|
||||
#[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
|
||||
fn build_in_page(html: &str) -> Option<&str> {
|
||||
const HEAD: &str = "fieldcraft-web-";
|
||||
const TAIL: &str = "_bg.wasm";
|
||||
let mut rest = html;
|
||||
while let Some(at) = rest.find(HEAD) {
|
||||
let candidate = rest.get(at..)?;
|
||||
let hash = candidate.get(HEAD.len()..)?;
|
||||
let len = hash.bytes().take_while(u8::is_ascii_alphanumeric).count();
|
||||
if len > 0 && hash.get(len..)?.starts_with(TAIL) {
|
||||
return candidate.get(..HEAD.len() + len + TAIL.len());
|
||||
}
|
||||
rest = candidate.get(HEAD.len()..)?;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The name a file from the computer is kept under in the page: its last path part, without
|
||||
/// characters a path would read as folders.
|
||||
#[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
|
||||
@@ -64,6 +88,18 @@ mod tests {
|
||||
assert_eq!(sample_in_query("?samples=x"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_running_build_is_found_in_the_page() {
|
||||
let page = r#"<link rel="modulepreload" href="/fieldcraft/fieldcraft-web-1a2b3c.js"><link rel="preload" href="/fieldcraft/fieldcraft-web-1a2b3c_bg.wasm" as="fetch">"#;
|
||||
assert_eq!(build_in_page(page), Some("fieldcraft-web-1a2b3c_bg.wasm"));
|
||||
let next = page.replace("1a2b3c", "9f8e7d");
|
||||
assert_ne!(build_in_page(page), build_in_page(&next));
|
||||
// A development page (no hash) and other text: nothing to compare.
|
||||
assert_eq!(build_in_page(r#"<script src="fieldcraft-web.js"></script>"#), None);
|
||||
assert_eq!(build_in_page("fieldcraft-web-"), None);
|
||||
assert_eq!(build_in_page(""), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_names_stay_in_their_folder() {
|
||||
assert_eq!(safe_name("beam.fieldcraft"), "beam.fieldcraft");
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
//! Anonymous usage in the browser (docs/privacy.md): the same events and the same consent as the
|
||||
//! desktop app, the choice kept in the browser's local storage with the other preferences. Queued
|
||||
//! events are posted with `fetch` every half minute and when the page is closed or left (`keepalive`, so
|
||||
//! a closing page still sends them); a failed post is dropped silently.
|
||||
//!
|
||||
//! The project key is a build setting, `FIELDCRAFT_POSTHOG_KEY`: a build without one asks nothing
|
||||
//! and sends nothing.
|
||||
|
||||
use fieldcraft_engine::usage;
|
||||
use fieldcraft_ui_egui::files::PrefsStore;
|
||||
use fieldcraft_ui_egui::privacy::UsageHost;
|
||||
use wasm_bindgen::JsCast as _;
|
||||
|
||||
const KEY: Option<&str> = option_env!("FIELDCRAFT_POSTHOG_KEY");
|
||||
/// Where the preferences are kept in local storage.
|
||||
const PREFS_KEY: &str = "fieldcraft-prefs";
|
||||
/// How often queued events are sent (seconds).
|
||||
pub const INTERVAL: f64 = 30.0;
|
||||
|
||||
fn key() -> Option<&'static str> {
|
||||
KEY.map(str::trim).filter(|k| !k.is_empty())
|
||||
}
|
||||
|
||||
fn local_storage() -> Option<web_sys::Storage> {
|
||||
web_sys::window()?.local_storage().ok().flatten()
|
||||
}
|
||||
|
||||
/// The preferences in local storage (navigation, privacy).
|
||||
pub fn prefs_store() -> PrefsStore {
|
||||
PrefsStore {
|
||||
load: Box::new(|| local_storage()?.get_item(PREFS_KEY).ok().flatten().map(String::into_bytes)),
|
||||
save: Box::new(|bytes| {
|
||||
let text = std::str::from_utf8(bytes).map_err(|e| e.to_string())?;
|
||||
local_storage().ok_or("browser storage is turned off")?.set_item(PREFS_KEY, text).map_err(crate::web::js_err)
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// What the window needs to ask and record, when the build has a key.
|
||||
pub fn host() -> Option<UsageHost> {
|
||||
// The browser's clock for command durations (the plain wasm target has none).
|
||||
usage::set_clock(js_sys::Date::now);
|
||||
key().is_some().then(|| UsageHost {
|
||||
platform: "web",
|
||||
os: "web",
|
||||
arch: "wasm32",
|
||||
new_id: Box::new(|| web_sys::window()?.crypto().ok().map(|c| c.random_uuid())),
|
||||
})
|
||||
}
|
||||
|
||||
/// Post what is queued.
|
||||
pub fn send() {
|
||||
let (Some(key), Some(window)) = (key(), web_sys::window()) else { return };
|
||||
let url = format!("{}/batch/", usage::DEFAULT_HOST);
|
||||
while let Some(batch) = usage::take_batch() {
|
||||
let init = web_sys::RequestInit::new();
|
||||
init.set_method("POST");
|
||||
init.set_body(&wasm_bindgen::JsValue::from_str(&batch.body(key)));
|
||||
// The Fetch standard's `keepalive` (a closing page still sends it); web-sys has no setter.
|
||||
let _ = js_sys::Reflect::set(&init, &"keepalive".into(), &true.into());
|
||||
let headers = web_sys::Headers::new().ok();
|
||||
if let Some(h) = &headers {
|
||||
let _ = h.set("Content-Type", "application/json");
|
||||
init.set_headers(h);
|
||||
}
|
||||
let promise = window.fetch_with_str_and_init(&url, &init);
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
// Offline or refused: the batch is dropped.
|
||||
if let Err(e) = wasm_bindgen_futures::JsFuture::from(promise).await {
|
||||
log::debug!("usage: not sent: {}", crate::web::js_err(e));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// When the page is closed or left: the session's length, then send.
|
||||
pub fn send_when_hidden(window: &web_sys::Window) {
|
||||
let on_hide = wasm_bindgen::closure::Closure::<dyn FnMut()>::new(|| {
|
||||
usage::closing();
|
||||
send();
|
||||
});
|
||||
if let Err(e) = window.add_event_listener_with_callback("pagehide", on_hide.as_ref().unchecked_ref()) {
|
||||
log::warn!("usage: {}", crate::web::js_err(e));
|
||||
}
|
||||
on_hide.forget();
|
||||
}
|
||||
@@ -74,6 +74,7 @@ pub fn start() {
|
||||
fieldcraft_io::recovery::set_clock(|| js_sys::Date::now().max(0.0) as u64);
|
||||
let Some(window) = web_sys::window() else { return };
|
||||
ask_before_unload(&window);
|
||||
crate::usage::send_when_hidden(&window);
|
||||
let Some(canvas) = element(CANVAS_ID).and_then(|e| e.dyn_into::<web_sys::HtmlCanvasElement>().ok()) else {
|
||||
log::error!("missing <canvas id=\"{CANVAS_ID}\">");
|
||||
return;
|
||||
@@ -86,6 +87,10 @@ pub fn start() {
|
||||
Box::new(|cc| {
|
||||
let inbox = Inbox::default();
|
||||
let mut app = ModelApp::new(Session::default()).with_services(services(inbox.clone(), cc.egui_ctx.clone()));
|
||||
// Anonymous usage: asked once, recorded only when the user agreed (docs/privacy.md).
|
||||
if let Some(host) = crate::usage::host() {
|
||||
app = app.with_usage(host);
|
||||
}
|
||||
if let Some(rs) = &cc.wgpu_render_state {
|
||||
let info = rs.adapter.get_info();
|
||||
log::info!("fieldcraft-web: graphics {:?} {}, MSAA {}x", info.backend, info.name, rs.msaa_samples);
|
||||
@@ -102,7 +107,8 @@ pub fn start() {
|
||||
if recoverable > 0 {
|
||||
app.set_status(format!("{recoverable} autosaved model(s) can be recovered: File › Recover…"), false);
|
||||
}
|
||||
Ok(Box::new(Shell { app, inbox, store, autosaver, autosaved_at: 0.0, storage_error: false }))
|
||||
let deploy = crate::deploy::Watch::start();
|
||||
Ok(Box::new(Shell { app, inbox, store, autosaver, autosaved_at: 0.0, storage_error: false, sent_at: 0.0, deploy }))
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
@@ -188,6 +194,10 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services {
|
||||
pick_save: Some(Box::new(|name: &str, _: &[Filter]| Some(page_path(name)))),
|
||||
// The recent list holds the page's files, which go with the page.
|
||||
recent_path: None,
|
||||
// Preferences are kept in the browser's local storage.
|
||||
prefs: Some(crate::usage::prefs_store()),
|
||||
// egui opens links itself in the browser.
|
||||
open_url: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -202,6 +212,10 @@ struct Shell {
|
||||
autosaved_at: f64,
|
||||
/// The last autosave did not fit in the browser's storage (said once until one fits).
|
||||
storage_error: bool,
|
||||
/// App time usage events were last sent.
|
||||
sent_at: f64,
|
||||
/// Looks for a new deployment of the app.
|
||||
deploy: crate::deploy::Watch,
|
||||
}
|
||||
|
||||
impl Shell {
|
||||
@@ -267,7 +281,19 @@ impl eframe::App for Shell {
|
||||
self.open_arrived();
|
||||
self.app.logic(ctx);
|
||||
self.autosave(ctx);
|
||||
if self.app.now - self.sent_at >= crate::usage::INTERVAL {
|
||||
self.sent_at = self.app.now;
|
||||
crate::usage::send();
|
||||
}
|
||||
UNSAVED.with(|u| u.set(self.app.session.is_dirty() && !self.app.session.journal.is_empty()));
|
||||
if self.app.now - self.deploy.looked_at >= crate::deploy::INTERVAL || self.app.now < self.deploy.looked_at {
|
||||
self.deploy.looked_at = self.app.now;
|
||||
self.deploy.look();
|
||||
}
|
||||
if self.deploy.found() && !self.app.reload_offered() {
|
||||
self.app.offer_reload(Box::new(crate::deploy::reload));
|
||||
}
|
||||
ctx.request_repaint_after(std::time::Duration::from_secs_f64(crate::deploy::INTERVAL));
|
||||
}
|
||||
|
||||
/// Dropped files are read here (browsers read them asynchronously) and arrive through the
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "fieldcraft"
|
||||
description = "FieldCraft desktop app"
|
||||
description = "Finite element modeling: meshing, model setup, solver decks and a linear solver"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
@@ -13,12 +13,98 @@ workspace = true
|
||||
fieldcraft-engine = { workspace = true }
|
||||
fieldcraft-ui-egui = { workspace = true }
|
||||
fieldcraft-io = { workspace = true }
|
||||
fieldcraft-update = { workspace = true }
|
||||
rfd = { workspace = true }
|
||||
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "wayland", "x11"] }
|
||||
egui = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
log = { workspace = true }
|
||||
# Usage analytics (docs/privacy.md): an HTTPS POST with rustls on ring, checked against the
|
||||
# operating system's certificates (no bundled root list), and a random install id.
|
||||
ureq = { version = "3.4", default-features = false, features = ["rustls-no-provider", "platform-verifier"] }
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring", "std"] }
|
||||
getrandom = "0.3"
|
||||
|
||||
[build-dependencies]
|
||||
# The Windows executable's icon resource (build.rs).
|
||||
embed-resource = "3.0.12"
|
||||
|
||||
# Linux .deb and .rpm packages (cargo-deb, cargo-generate-rpm), built by packaging/linux/package.sh
|
||||
# from the release binaries it has already built and stripped; it sets the version and the file
|
||||
# names. The file list matches the tar.gz's (package.sh's staged tree; the release workflow
|
||||
# compares them).
|
||||
# The binaries link only glibc and libgcc_s. Windowing (Wayland, X11, xkbcommon), the GPU (Vulkan
|
||||
# or EGL) and the file dialogs (the XDG desktop portal) are opened at run time, so they are no ELF
|
||||
# NEEDED entries and the tools cannot find them: they are listed here.
|
||||
[package.metadata.deb]
|
||||
name = "fieldcraft"
|
||||
maintainer = "FieldCraft contributors <[email protected]>"
|
||||
copyright = "FieldCraft contributors"
|
||||
section = "science"
|
||||
priority = "optional"
|
||||
extended-description = """\
|
||||
FieldCraft turns geometry into analysis-ready finite element models: volume \
|
||||
meshes, materials, sections, boundary conditions, loads and steps. It writes \
|
||||
Abaqus input, Nastran bulk data and LS-DYNA keyword decks, and solves linear \
|
||||
static and modal problems with its own solver. Includes fieldcraft-cli, a \
|
||||
headless command runner and MCP server."""
|
||||
depends = "$auto, libxkbcommon0, libxkbcommon-x11-0, libwayland-client0, libx11-6, libx11-xcb1, libxcb1, libxcursor1, libxi6, libvulkan1 | libegl1"
|
||||
recommends = "mesa-vulkan-drivers, libegl-mesa0, xdg-desktop-portal"
|
||||
assets = [
|
||||
["target/release/fieldcraft", "usr/bin/", "755"],
|
||||
["target/release/fieldcraft-cli", "usr/bin/", "755"],
|
||||
["../../packaging/linux/io.github.jyviko.fieldcraft.desktop", "usr/share/applications/", "644"],
|
||||
["../../assets/app-icon/icon.iconset/icon_16x16.png", "usr/share/icons/hicolor/16x16/apps/io.github.jyviko.fieldcraft.png", "644"],
|
||||
["../../assets/app-icon/icon.iconset/icon_32x32.png", "usr/share/icons/hicolor/32x32/apps/io.github.jyviko.fieldcraft.png", "644"],
|
||||
["../../assets/app-icon/icon.iconset/[email protected]", "usr/share/icons/hicolor/64x64/apps/io.github.jyviko.fieldcraft.png", "644"],
|
||||
["../../assets/app-icon/icon.iconset/icon_128x128.png", "usr/share/icons/hicolor/128x128/apps/io.github.jyviko.fieldcraft.png", "644"],
|
||||
["../../assets/app-icon/icon.iconset/icon_256x256.png", "usr/share/icons/hicolor/256x256/apps/io.github.jyviko.fieldcraft.png", "644"],
|
||||
["../../assets/app-icon/icon.iconset/icon_512x512.png", "usr/share/icons/hicolor/512x512/apps/io.github.jyviko.fieldcraft.png", "644"],
|
||||
["../../assets/app-icon/icon.iconset/[email protected]", "usr/share/icons/hicolor/1024x1024/apps/io.github.jyviko.fieldcraft.png", "644"],
|
||||
["../../README.md", "usr/share/doc/fieldcraft/", "644"],
|
||||
["../../LICENSE-MIT", "usr/share/doc/fieldcraft/", "644"],
|
||||
["../../LICENSE-APACHE", "usr/share/doc/fieldcraft/", "644"],
|
||||
["../../NOTICE", "usr/share/doc/fieldcraft/", "644"],
|
||||
["../../THIRD-PARTY-LICENSES.txt", "usr/share/doc/fieldcraft/", "644"],
|
||||
]
|
||||
|
||||
[package.metadata.generate-rpm]
|
||||
name = "fieldcraft"
|
||||
license = "MIT OR Apache-2.0"
|
||||
url = "https://github.com/jyviko/fieldcraft"
|
||||
assets = [
|
||||
{ source = "target/release/fieldcraft", dest = "/usr/bin/fieldcraft", mode = "755" },
|
||||
{ source = "target/release/fieldcraft-cli", dest = "/usr/bin/fieldcraft-cli", mode = "755" },
|
||||
{ source = "../../packaging/linux/io.github.jyviko.fieldcraft.desktop", dest = "/usr/share/applications/io.github.jyviko.fieldcraft.desktop", mode = "644" },
|
||||
{ source = "../../assets/app-icon/icon.iconset/icon_16x16.png", dest = "/usr/share/icons/hicolor/16x16/apps/io.github.jyviko.fieldcraft.png", mode = "644" },
|
||||
{ source = "../../assets/app-icon/icon.iconset/icon_32x32.png", dest = "/usr/share/icons/hicolor/32x32/apps/io.github.jyviko.fieldcraft.png", mode = "644" },
|
||||
{ source = "../../assets/app-icon/icon.iconset/[email protected]", dest = "/usr/share/icons/hicolor/64x64/apps/io.github.jyviko.fieldcraft.png", mode = "644" },
|
||||
{ source = "../../assets/app-icon/icon.iconset/icon_128x128.png", dest = "/usr/share/icons/hicolor/128x128/apps/io.github.jyviko.fieldcraft.png", mode = "644" },
|
||||
{ source = "../../assets/app-icon/icon.iconset/icon_256x256.png", dest = "/usr/share/icons/hicolor/256x256/apps/io.github.jyviko.fieldcraft.png", mode = "644" },
|
||||
{ source = "../../assets/app-icon/icon.iconset/icon_512x512.png", dest = "/usr/share/icons/hicolor/512x512/apps/io.github.jyviko.fieldcraft.png", mode = "644" },
|
||||
{ source = "../../assets/app-icon/icon.iconset/[email protected]", dest = "/usr/share/icons/hicolor/1024x1024/apps/io.github.jyviko.fieldcraft.png", mode = "644" },
|
||||
{ source = "../../README.md", dest = "/usr/share/doc/fieldcraft/README.md", mode = "644", doc = true },
|
||||
{ source = "../../LICENSE-MIT", dest = "/usr/share/doc/fieldcraft/LICENSE-MIT", mode = "644", doc = true },
|
||||
{ source = "../../LICENSE-APACHE", dest = "/usr/share/doc/fieldcraft/LICENSE-APACHE", mode = "644", doc = true },
|
||||
{ source = "../../NOTICE", dest = "/usr/share/doc/fieldcraft/NOTICE", mode = "644", doc = true },
|
||||
{ source = "../../THIRD-PARTY-LICENSES.txt", dest = "/usr/share/doc/fieldcraft/THIRD-PARTY-LICENSES.txt", mode = "644", doc = true },
|
||||
]
|
||||
# The binaries' ELF dependencies (glibc, libgcc_s) are found automatically; these are opened at run
|
||||
# time. Soname provides rather than package names, so the same requirements resolve on Fedora/RHEL
|
||||
# and openSUSE.
|
||||
require-sh = false
|
||||
|
||||
[package.metadata.generate-rpm.requires]
|
||||
"libxkbcommon.so.0()(64bit)" = "*"
|
||||
"libxkbcommon-x11.so.0()(64bit)" = "*"
|
||||
"libwayland-client.so.0()(64bit)" = "*"
|
||||
"libX11.so.6()(64bit)" = "*"
|
||||
"libX11-xcb.so.1()(64bit)" = "*"
|
||||
"libxcb.so.1()(64bit)" = "*"
|
||||
"libXcursor.so.1()(64bit)" = "*"
|
||||
"libXi.so.6()(64bit)" = "*"
|
||||
"(libvulkan.so.1()(64bit) or libEGL.so.1()(64bit))" = ""
|
||||
|
||||
[package.metadata.generate-rpm.recommends]
|
||||
mesa-vulkan-drivers = "*"
|
||||
xdg-desktop-portal = "*"
|
||||
@@ -12,9 +12,11 @@
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
mod control_server;
|
||||
mod update;
|
||||
mod usage;
|
||||
|
||||
use fieldcraft_engine::Session;
|
||||
use fieldcraft_engine::autosave::{self, Autosaver};
|
||||
use fieldcraft_engine::{Session, crash, logfile};
|
||||
use fieldcraft_ui_egui::{Filter, ModelApp, Services};
|
||||
|
||||
const USAGE: &str =
|
||||
@@ -47,6 +49,10 @@ struct App {
|
||||
autosaver: Option<Autosaver>,
|
||||
/// App time of the last autosave check.
|
||||
autosaved_at: f64,
|
||||
/// The first frame was drawn (the crash journal says the app is up).
|
||||
running: bool,
|
||||
/// Sends the anonymous usage events, when this run may (docs/privacy.md).
|
||||
usage: Option<usage::Sender>,
|
||||
}
|
||||
|
||||
impl App {
|
||||
@@ -61,6 +67,10 @@ impl App {
|
||||
|
||||
impl eframe::App for App {
|
||||
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||
if !self.running {
|
||||
self.running = true;
|
||||
crash::activity("running");
|
||||
}
|
||||
self.app.logic(ctx);
|
||||
if self.app.now - self.autosaved_at >= AUTOSAVE_SECONDS {
|
||||
self.autosaved_at = self.app.now;
|
||||
@@ -76,6 +86,16 @@ impl eframe::App for App {
|
||||
{
|
||||
log::warn!("autosave: {e}");
|
||||
}
|
||||
self.app.usage_closing();
|
||||
if let Some(u) = self.usage.take() {
|
||||
u.finish();
|
||||
}
|
||||
// An update the user chose to install: swapped in now that the window has closed.
|
||||
if let Some(staged) = self.app.take_staged_update() {
|
||||
update::finish(&staged);
|
||||
}
|
||||
log::info!("FieldCraft closed");
|
||||
crash::end_session();
|
||||
}
|
||||
fn raw_input_hook(&mut self, _ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
self.app.raw_input_hook(raw);
|
||||
@@ -95,9 +115,57 @@ fn services() -> Services {
|
||||
})),
|
||||
// Beside the recovery folder in the per-user data folder.
|
||||
recent_path: fieldcraft_io::recovery::default_dir().and_then(|d| d.parent().map(|p| p.join("recent.json"))),
|
||||
prefs: fieldcraft_io::recovery::default_dir()
|
||||
.and_then(|d| d.parent().map(|p| fieldcraft_ui_egui::files::PrefsStore::file(p.join("prefs.json")))),
|
||||
open_url: Some(Box::new(open_url)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Open a web link in the default browser, with the system's own opener: `open` (macOS),
|
||||
/// `xdg-open` (Linux and the BSDs), `explorer` (Windows). The link is one argument, never
|
||||
/// passed through a shell. Only https links are opened.
|
||||
fn open_url(url: &str) -> Result<(), String> {
|
||||
if !url.starts_with("https://") {
|
||||
return Err(format!("not a web link: {}", url.chars().take(80).collect::<String>()));
|
||||
}
|
||||
let opener = if cfg!(target_os = "macos") {
|
||||
"open"
|
||||
} else if cfg!(windows) {
|
||||
"explorer"
|
||||
} else {
|
||||
"xdg-open"
|
||||
};
|
||||
let mut child = std::process::Command::new(opener).arg(url).spawn().map_err(|e| format!("{opener}: {e}"))?;
|
||||
// Reaped off the window thread; its exit status says nothing (`explorer` exits with 1 even
|
||||
// when it opened the link).
|
||||
std::thread::spawn(move || {
|
||||
let _ = child.wait();
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Crash reports and the log file (docs/crash-reports.md): reports of earlier runs that crashed
|
||||
/// come back, for the window to offer. Both live in the app's data folder (a temporary one in
|
||||
/// runs driven by automation); `FIELDCRAFT_CRASH_DIR` moves the crash folder.
|
||||
fn start_reporting() -> Vec<crash::Summary> {
|
||||
// First the crash reports: an unclean exit's report takes the dead run's lines from the log.
|
||||
let crashed = crash::default_dir().map(|dir| crash::install(dir, crash::Build::current())).unwrap_or_default();
|
||||
match fieldcraft_io::recovery::data_dir().map(|d| logfile::install(&d.join("logs"), log::LevelFilter::Info)) {
|
||||
Some(Ok(path)) => eprintln!("fieldcraft: log {}", path.display()),
|
||||
Some(Err(e)) => eprintln!("fieldcraft: no log file: {e}"),
|
||||
None => {}
|
||||
}
|
||||
let b = crash::Build::current();
|
||||
log::info!(
|
||||
"FieldCraft {} started ({}), crash reports in {}",
|
||||
b.version,
|
||||
b.version_line(),
|
||||
crash::default_dir().map(|d| d.display().to_string()).unwrap_or_default()
|
||||
);
|
||||
crash::activity("startup");
|
||||
crashed
|
||||
}
|
||||
|
||||
/// Command-line options.
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
struct Args {
|
||||
@@ -149,6 +217,12 @@ fn main() -> eframe::Result {
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
if args.control.is_some() {
|
||||
// A run driven by automation keeps its autosaves (and recent files and preferences, which
|
||||
// live beside them), its crash reports and its log in a temporary folder, never the user's.
|
||||
fieldcraft_io::recovery::use_automation_dir();
|
||||
}
|
||||
let crashed = start_reporting();
|
||||
let options = eframe::NativeOptions {
|
||||
viewport: egui::ViewportBuilder::default()
|
||||
.with_title("FieldCraft")
|
||||
@@ -171,12 +245,26 @@ fn main() -> eframe::Result {
|
||||
"FieldCraft",
|
||||
options,
|
||||
Box::new(move |cc| {
|
||||
let mut app = ModelApp::new(Session::default()).with_services(services());
|
||||
let mut session = Session::default();
|
||||
// The window's model: its commands go into the crash journal.
|
||||
session.crash_journal = crash::enabled();
|
||||
let mut app = ModelApp::new(session).with_services(services());
|
||||
// Anonymous usage: asked once, recorded only when the user agreed (docs/privacy.md).
|
||||
let usage = match usage::host(args.control.is_some()) {
|
||||
Some(host) => {
|
||||
app = app.with_usage(host);
|
||||
usage::start()
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
// Updates (docs/updates.md): checked at most daily when on, installed only on a click.
|
||||
fieldcraft_engine::enable_update_checks(true);
|
||||
app = app.with_updates(update::host(cc.egui_ctx.clone(), args.control.is_some()));
|
||||
app.custom_titlebar = CUSTOM_TITLEBAR;
|
||||
app.integrated_titlebar = cfg!(target_os = "macos");
|
||||
if let Some(rs) = &cc.wgpu_render_state {
|
||||
let info = rs.adapter.get_info();
|
||||
eprintln!("fieldcraft: graphics {:?} {}, MSAA {}x (requested {MSAA}x)", info.backend, info.name, rs.msaa_samples);
|
||||
log::info!("graphics {:?} {} ({}), MSAA {}x (requested {MSAA}x)", info.backend, info.name, info.driver, rs.msaa_samples);
|
||||
app.set_wgpu(rs, DEPTH_BITS, rs.msaa_samples, &cc.egui_ctx);
|
||||
}
|
||||
if let Some(port) = args.control {
|
||||
@@ -196,7 +284,8 @@ fn main() -> eframe::Result {
|
||||
}
|
||||
Autosaver::new(&dir).map_err(|e| log::warn!("autosave unavailable: {e}")).ok()
|
||||
});
|
||||
Ok(Box::new(App { app, autosaver, autosaved_at: 0.0 }))
|
||||
app.announce_crashes(&crashed);
|
||||
Ok(Box::new(App { app, autosaver, autosaved_at: 0.0, running: false, usage }))
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
//! The desktop app's side of updates (docs/updates.md): it runs the window's update jobs
|
||||
//! ([`fieldcraft_ui_egui::updates`]) on background threads with [`fieldcraft_update`], and swaps
|
||||
//! a staged release in after the window has closed ([`finish`]).
|
||||
//!
|
||||
//! Automatic checks are off in runs driven by automation (`--control`) and under CI, so test
|
||||
//! and agent runs never reach GitHub on their own; `FIELDCRAFT_UPDATE_HOST` (a local test
|
||||
//! server) turns them back on. Help › Check for Updates works in every run.
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::path::Path;
|
||||
use std::sync::mpsc;
|
||||
|
||||
use fieldcraft_ui_egui::updates::{Event, Job, UpdateHost};
|
||||
use fieldcraft_update::install::{self, Finish, Install};
|
||||
use fieldcraft_update::net::{Client, Which};
|
||||
use fieldcraft_update::stage::{self, Options};
|
||||
use fieldcraft_update::{Release, Staged};
|
||||
|
||||
/// What the window needs for updates.
|
||||
pub fn host(ctx: egui::Context, automation: bool) -> UpdateHost {
|
||||
let here = install::here();
|
||||
log::info!("updates: {}", here.describe());
|
||||
stage::clean_stale(&here);
|
||||
let env = |k: &str| std::env::var_os(k).is_some_and(|v| !v.is_empty());
|
||||
let automatic = env(fieldcraft_update::HOST_ENV) || !(automation || env("CI"));
|
||||
let (tx, events) = mpsc::channel::<Event>();
|
||||
let unsupported = here.unsupported();
|
||||
let start = move |job: Job| {
|
||||
let (tx, ctx, here) = (tx.clone(), ctx.clone(), here.clone());
|
||||
let spawned = std::thread::Builder::new().name("fieldcraft update".into()).spawn(move || {
|
||||
let send = |e: Event| {
|
||||
let _ = tx.send(e);
|
||||
ctx.request_repaint();
|
||||
};
|
||||
let client = Client::from_env();
|
||||
match job {
|
||||
Job::Check { manual } => send(Event::Checked { manual, result: client.check().map_err(|e| e.to_string()) }),
|
||||
Job::Stage(release) => send(Event::Staged(stage_release(&client, &release, &here, &send))),
|
||||
Job::Reinstall => {
|
||||
let staged = client
|
||||
.release(&Which::Version(fieldcraft_update::current()))
|
||||
.map_err(|e| e.to_string())
|
||||
.and_then(|r| stage_release(&client, &r, &here, &send));
|
||||
send(Event::Staged(staged));
|
||||
}
|
||||
}
|
||||
});
|
||||
if let Err(e) = spawned {
|
||||
log::warn!("updates: no thread: {e}");
|
||||
}
|
||||
};
|
||||
UpdateHost { unsupported, automatic, start: Box::new(start), events, now: Box::new(now), open_file: Box::new(open_file) }
|
||||
}
|
||||
|
||||
/// Download, verify and stage `release`, reporting each whole percent.
|
||||
fn stage_release(client: &Client, release: &Release, here: &Install, send: &dyn Fn(Event)) -> Result<Staged, String> {
|
||||
let downloads = fieldcraft_io::recovery::data_dir().map(|d| d.join("updates")).unwrap_or_else(|| std::env::temp_dir().join("fieldcraft-updates"));
|
||||
let last = Cell::new(u64::MAX);
|
||||
let progress = |done: u64, total: u64| {
|
||||
let step = done.saturating_mul(100).checked_div(total).unwrap_or(done / (1024 * 1024));
|
||||
if last.replace(step) != step {
|
||||
send(Event::Progress(done, total));
|
||||
}
|
||||
};
|
||||
let options = Options { key: fieldcraft_update::PUBLIC_KEY, downloads: &downloads, arch: std::env::consts::ARCH, progress: &progress };
|
||||
let staged = stage::stage(client, release, here, &options).map_err(|e| e.to_string());
|
||||
match &staged {
|
||||
Ok(s) => log::info!("updates: FieldCraft {} verified and staged at {}", s.version, s.payload.display()),
|
||||
Err(e) => log::warn!("updates: FieldCraft {} not staged: {e}", release.version),
|
||||
}
|
||||
staged
|
||||
}
|
||||
|
||||
/// Swap `staged` in and start it: the window has closed, its autosave is closed.
|
||||
pub fn finish(staged: &Staged) {
|
||||
match install::plan(staged, true) {
|
||||
Ok(Finish::Swap(plan)) => match stage::apply(&plan) {
|
||||
Ok(()) => log::info!("updates: FieldCraft {} installed ({})", staged.version, staged.install.describe()),
|
||||
Err(e) => log::error!("updates: FieldCraft {} not installed, the previous version is kept: {e}", staged.version),
|
||||
},
|
||||
Ok(Finish::Package { .. }) => {}
|
||||
Err(e) => log::error!("updates: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Seconds since the Unix epoch.
|
||||
fn now() -> u64 {
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Open a downloaded package with the system's handler for it (Linux: the software installer).
|
||||
fn open_file(path: &Path) -> Result<(), String> {
|
||||
let opener = if cfg!(target_os = "macos") {
|
||||
"open"
|
||||
} else if cfg!(windows) {
|
||||
"explorer"
|
||||
} else {
|
||||
"xdg-open"
|
||||
};
|
||||
let mut child = std::process::Command::new(opener).arg(path).spawn().map_err(|e| format!("{opener}: {e}"))?;
|
||||
std::thread::spawn(move || {
|
||||
let _ = child.wait();
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
//! Sending the anonymous usage events (docs/privacy.md) to PostHog Cloud EU: a background
|
||||
//! thread posts the queued events ([`fieldcraft_engine::usage`]) in batches every half minute and
|
||||
//! when the window closes. A failed post (offline, a slow network) drops its batch silently;
|
||||
//! nothing waits on it but the thread.
|
||||
//!
|
||||
//! The project key is a build setting, `FIELDCRAFT_POSTHOG_KEY`, which only the release workflow
|
||||
//! sets: local, development and fork builds have none and send nothing.
|
||||
|
||||
use std::sync::mpsc;
|
||||
use std::time::Duration;
|
||||
|
||||
use fieldcraft_engine::usage;
|
||||
use fieldcraft_ui_egui::privacy::UsageHost;
|
||||
|
||||
/// The PostHog project key the release build was made with.
|
||||
const KEY: Option<&str> = option_env!("FIELDCRAFT_POSTHOG_KEY");
|
||||
/// How often queued events are sent.
|
||||
const INTERVAL: Duration = Duration::from_secs(30);
|
||||
/// The longest one post may take.
|
||||
const TIMEOUT: Duration = Duration::from_secs(10);
|
||||
/// How long closing the window waits for the last batch.
|
||||
const LAST_WAIT: Duration = Duration::from_secs(2);
|
||||
|
||||
fn key() -> Option<&'static str> {
|
||||
KEY.map(str::trim).filter(|k| !k.is_empty())
|
||||
}
|
||||
|
||||
/// What the window needs to ask and record, when this run may share usage: the build has a key,
|
||||
/// `FIELDCRAFT_TELEMETRY` is not `0`, and neither CI nor `--control` automation runs it (unless
|
||||
/// `FIELDCRAFT_TELEMETRY=1`).
|
||||
pub fn host(automation: bool) -> Option<UsageHost> {
|
||||
let telemetry = std::env::var("FIELDCRAFT_TELEMETRY").ok();
|
||||
let ci = std::env::var_os("CI").is_some_and(|v| !v.is_empty());
|
||||
usage::allowed(key().is_some(), telemetry.as_deref(), automation, ci).then(|| UsageHost {
|
||||
platform: "desktop",
|
||||
os: std::env::consts::OS,
|
||||
arch: std::env::consts::ARCH,
|
||||
new_id: Box::new(new_id),
|
||||
})
|
||||
}
|
||||
|
||||
/// A random (version 4) UUID from the operating system's random source.
|
||||
fn new_id() -> Option<String> {
|
||||
let mut b = [0u8; 16];
|
||||
getrandom::fill(&mut b).ok()?;
|
||||
b[6] = (b[6] & 0x0f) | 0x40;
|
||||
b[8] = (b[8] & 0x3f) | 0x80;
|
||||
let hex: String = b.iter().map(|x| format!("{x:02x}")).collect();
|
||||
Some(format!("{}-{}-{}-{}-{}", &hex[..8], &hex[8..12], &hex[12..16], &hex[16..20], &hex[20..]))
|
||||
}
|
||||
|
||||
/// The sending thread; [`Sender::finish`] sends what is left and stops it.
|
||||
pub struct Sender {
|
||||
stop: mpsc::Sender<()>,
|
||||
finished: mpsc::Receiver<()>,
|
||||
}
|
||||
|
||||
/// Start the sending thread (only when the build has a key). `FIELDCRAFT_TELEMETRY_HOST`
|
||||
/// replaces PostHog's host, for checking the payload against a local listener.
|
||||
pub fn start() -> Option<Sender> {
|
||||
let key = key()?;
|
||||
let host = std::env::var("FIELDCRAFT_TELEMETRY_HOST").ok().filter(|h| !h.trim().is_empty()).unwrap_or_else(|| usage::DEFAULT_HOST.into());
|
||||
let url = format!("{}/batch/", host.trim_end_matches('/'));
|
||||
// rustls's process-wide crypto (ring); another part of the app may have installed it first.
|
||||
let _ = rustls::crypto::ring::default_provider().install_default();
|
||||
let agent: ureq::Agent = ureq::Agent::config_builder()
|
||||
.timeout_global(Some(TIMEOUT))
|
||||
.tls_config(ureq::tls::TlsConfig::builder().root_certs(ureq::tls::RootCerts::PlatformVerifier).build())
|
||||
.build()
|
||||
.into();
|
||||
let (stop, stopped) = mpsc::channel::<()>();
|
||||
let (done, finished) = mpsc::channel::<()>();
|
||||
let spawned = std::thread::Builder::new().name("fieldcraft usage".into()).spawn(move || {
|
||||
loop {
|
||||
let last = !matches!(stopped.recv_timeout(INTERVAL), Err(mpsc::RecvTimeoutError::Timeout));
|
||||
while let Some(batch) = usage::take_batch() {
|
||||
if let Err(e) = agent.post(&url).header("Content-Type", "application/json").send(batch.body(key)) {
|
||||
// Offline or refused: this batch is dropped, the rest waits for the next try.
|
||||
log::debug!("usage: {} event(s) not sent: {e}", batch.events.len());
|
||||
break;
|
||||
}
|
||||
}
|
||||
if last {
|
||||
let _ = done.send(());
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
match spawned {
|
||||
Ok(_) => Some(Sender { stop, finished }),
|
||||
Err(e) => {
|
||||
log::warn!("usage: no sending thread: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Sender {
|
||||
/// Send what is queued (waiting briefly) and stop.
|
||||
pub fn finish(self) {
|
||||
let _ = self.stop.send(());
|
||||
let _ = self.finished.recv_timeout(LAST_WAIT);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn install_ids_are_random_version_4_uuids() {
|
||||
let (a, b) = (super::new_id().unwrap(), super::new_id().unwrap());
|
||||
assert_ne!(a, b);
|
||||
assert_eq!(a.len(), 36);
|
||||
assert_eq!(a.as_bytes()[14], b'4');
|
||||
assert!(matches!(a.as_bytes()[19], b'8' | b'9' | b'a' | b'b'), "{a}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
|
||||
<title>diagnostics.bug_report</title>
|
||||
<g id="Layer_1" data-name="Layer 1">
|
||||
<path d="M12 8.5 L12 8.5 C14.209 8.5 16 10.291 16 12.5 L16 15.5 C16 17.709 14.209 19.5 12 19.5 L12 19.5 C9.791 19.5 8 17.709 8 15.5 L8 12.5 C8 10.291 9.791 8.5 12 8.5 Z" fill="none" stroke="#dde2ea" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M9.9 5.8 C9.9 4.64 10.84 3.7 12 3.7 C13.16 3.7 14.1 4.64 14.1 5.8 C14.1 6.96 13.16 7.9 12 7.9 C10.84 7.9 9.9 6.96 9.9 5.8 Z" fill="none" stroke="#dde2ea" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M12 10.5 L12 18" fill="none" stroke="#4f9ce8" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M8 11.5 L4.8 9.8" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M8 14.5 L4.4 14.5" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M8.3 17.4 L5 19.4" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M16 11.5 L19.2 9.8" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M16 14.5 L19.6 14.5" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M15.7 17.4 L19 19.4" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.6 KiB |
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
|
||||
<title>geometry.datum.axis</title>
|
||||
<g id="Layer_1" data-name="Layer 1">
|
||||
<path d="M7 17 L19 5" fill="none" stroke="#4f9ce8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M20 4 L15 5.2 M20 4 L18.8 9" fill="none" stroke="#4f9ce8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M5.5 18.5 L2.5 21.5" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="1.5 2"/>
|
||||
<path d="M8.8 12 C8.8 10.233 10.233 8.8 12 8.8 C13.767 8.8 15.2 10.233 15.2 12 C15.2 13.767 13.767 15.2 12 15.2 C10.233 15.2 8.8 13.767 8.8 12 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M10.6 12 C10.6 11.227 11.227 10.6 12 10.6 C12.773 10.6 13.4 11.227 13.4 12 C13.4 12.773 12.773 13.4 12 13.4 C11.227 13.4 10.6 12.773 10.6 12 Z" fill="#f0b44a"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.1 KiB |
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
|
||||
<title>geometry.datum.point</title>
|
||||
<g id="Layer_1" data-name="Layer 1">
|
||||
<path d="M3 16 L9 10 L21 10 L15 16 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M12 3 L12 11 M8 7 L16 7" fill="none" stroke="#4f9ce8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M10.2 7 C10.2 6.006 11.006 5.2 12 5.2 C12.994 5.2 13.8 6.006 13.8 7 C13.8 7.994 12.994 8.8 12 8.8 C11.006 8.8 10.2 7.994 10.2 7 Z" fill="#f0b44a"/>
|
||||
<path d="M12 12.5 L12 20" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="1.5 2"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 846 B |
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
|
||||
<title>mesh.hex.blocks</title>
|
||||
<title>mesh.cells</title>
|
||||
<g id="Layer_1" data-name="Layer 1">
|
||||
<path d="M12 3 L20 7 L20 16 L12 20 L4 16 L4 7 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M4 7 L12 11 L20 7 M12 11 L12 20" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
|
Before Width: | Height: | Size: 1008 B After Width: | Height: | Size: 1003 B |
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
|
||||
<title>mesh.hex.mapped</title>
|
||||
<title>mesh.hex.generate</title>
|
||||
<g id="Layer_1" data-name="Layer 1">
|
||||
<path d="M12 3 L20 7 L20 16 L12 20 L4 16 L4 7 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M4 7 L12 11 L20 7 M12 11 L12 20" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
|
Before Width: | Height: | Size: 882 B After Width: | Height: | Size: 884 B |
@@ -1,10 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
|
||||
<title>mesh.hex.sweep</title>
|
||||
<g id="Layer_1" data-name="Layer 1">
|
||||
<path d="M3 8 L12 8 L12 17 L3 17 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M7.5 8 L7.5 17 M3 12.5 L12 12.5" fill="none" stroke="#dde2ea" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M3 8 L8 4 L21 4 L21 13 L12 17 M12 8 L21 4" fill="none" stroke="#dde2ea" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M14 13 L20 10 M18.17 12.63 L20 10 L16.8 9.88" fill="none" stroke="#4f9ce8" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 825 B |
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
|
||||
<title>mesh.size.seed</title>
|
||||
<title>mesh.seed.edge</title>
|
||||
<g id="Layer_1" data-name="Layer 1">
|
||||
<path d="M3 19 C7 5 17 5 21 19" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M1.7 19 C1.7 18.282 2.282 17.7 3 17.7 C3.718 17.7 4.3 18.282 4.3 19 C4.3 19.718 3.718 20.3 3 20.3 C2.282 20.3 1.7 19.718 1.7 19 Z" fill="#4f9ce8"/>
|
||||
|
Before Width: | Height: | Size: 1.5 KiB After Width: | Height: | Size: 1.5 KiB |
@@ -0,0 +1 @@
|
||||
{"shapes": [{"rect": [8, 8.5, 8, 11], "radius": 4, "stroke": "line", "width": 1.6}, {"circle": [12, 5.8, 2.1], "stroke": "line", "width": 1.6}, {"line": [12, 10.5, 12, 18], "stroke": "accent", "width": 1.5}, {"line": [8, 11.5, 4.8, 9.8], "stroke": "line"}, {"line": [8, 14.5, 4.4, 14.5], "stroke": "line"}, {"line": [8.3, 17.4, 5, 19.4], "stroke": "line"}, {"line": [16, 11.5, 19.2, 9.8], "stroke": "line"}, {"line": [16, 14.5, 19.6, 14.5], "stroke": "line"}, {"line": [15.7, 17.4, 19, 19.4], "stroke": "line"}]}
|
||||
@@ -0,0 +1 @@
|
||||
{"shapes": [{"d": "M7 17 L19 5", "stroke": "accent", "width": 2}, {"d": "M20 4 L15 5.2 M20 4 L18.8 9", "stroke": "accent", "width": 2}, {"d": "M5.5 18.5 L2.5 21.5", "stroke": "line", "dash": [1.5, 2]}, {"circle": [12, 12, 3.2], "fill": "soft", "stroke": "line", "width": 1.25}, {"circle": [12, 12, 1.4], "fill": "warm", "stroke": null}]}
|
||||
@@ -0,0 +1 @@
|
||||
{"shapes": [{"d": "M3 16 L9 10 L21 10 L15 16 Z", "fill": "soft", "stroke": "line", "width": 1.25}, {"d": "M12 3 L12 11 M8 7 L16 7", "stroke": "accent", "width": 2}, {"circle": [12, 7, 1.8], "fill": "warm", "stroke": null}, {"d": "M12 12.5 L12 20", "stroke": "line", "dash": [1.5, 2]}]}
|
||||
@@ -1 +0,0 @@
|
||||
{"shapes": [{"rect": [3, 8, 9, 9], "fill": "soft", "stroke": "line"}, {"d": "M7.5 8 L7.5 17 M3 12.5 L12 12.5", "stroke": "line", "width": 1}, {"d": "M3 8 L8 4 L21 4 L21 13 L12 17 M12 8 L21 4", "stroke": "line", "width": 1.25}, {"d": "M14 13 L20 10 M18.17 12.63 L20 10 L16.8 9.88", "stroke": "accent", "width": 1.5}]}
|
||||
@@ -0,0 +1 @@
|
||||
{"shapes": [{"d": "M2.5 13 C5.5 7.5 18.5 7.5 21.5 13 C18.5 18.5 5.5 18.5 2.5 13 Z", "fill": "soft", "stroke": "line"}, {"circle": [12, 13, 2.6], "fill": "accent", "stroke": "accent", "width": 1}, {"d": "M12 2.5 L12 5 M5.5 4.5 L7 6.5 M18.5 4.5 L17 6.5", "stroke": "warm", "width": 1.5}]}
|
||||
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
|
||||
<title>view.show_all</title>
|
||||
<g id="Layer_1" data-name="Layer 1">
|
||||
<path d="M2.5 13 C5.5 7.5 18.5 7.5 21.5 13 C18.5 18.5 5.5 18.5 2.5 13 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M9.4 13 C9.4 11.564 10.564 10.4 12 10.4 C13.436 10.4 14.6 11.564 14.6 13 C14.6 14.436 13.436 15.6 12 15.6 C10.564 15.6 9.4 14.436 9.4 13 Z" fill="#4f9ce8" stroke="#4f9ce8" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M12 2.5 L12 5 M5.5 4.5 L7 6.5 M18.5 4.5 L17 6.5" fill="none" stroke="#f0b44a" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 820 B |
@@ -25,6 +25,9 @@ serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
log = { workspace = true }
|
||||
# app.update.check (docs/updates.md); the browser build has no update check.
|
||||
fieldcraft-update = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
png = { workspace = true }
|
||||
zip = { workspace = true }
|
||||
@@ -47,6 +47,7 @@ impl Autosaver {
|
||||
let bytes = s.file_bytes(None)?;
|
||||
self.slot.write(&bytes, s.path.as_deref(), s.model.nodes().len(), s.model.elements().len())?;
|
||||
self.saved = Some(s.revision());
|
||||
crate::crash::autosaved(s, &self.slot.file());
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
@@ -84,6 +85,7 @@ mod tests {
|
||||
let listed = s.execute("file.recovery.list", &json!({"dir": dir})).unwrap();
|
||||
assert_eq!(listed[0]["id"], id);
|
||||
assert_eq!(listed[0]["nodes"], 1);
|
||||
assert!(listed[0]["age"].as_u64().is_some_and(|a| a < 60), "{listed}");
|
||||
let mut next = Session::default();
|
||||
let r = next.execute("file.recover", &json!({"id": id, "dir": dir})).unwrap();
|
||||
assert_eq!(r["nodes"], 1);
|
||||
|
||||
@@ -0,0 +1,393 @@
|
||||
//! Bug report drafts (Help › Report a Bug, and Report it after a crash): a GitHub new-issue link
|
||||
//! that fills in the bug form (`.github/ISSUE_TEMPLATE/bug.yml`), and the files to attach.
|
||||
//!
|
||||
//! Nothing here sends anything. The user reviews the draft, then their browser opens the issue
|
||||
//! form, which they submit or not.
|
||||
//!
|
||||
//! What a draft holds by default: the version, the OS, what went wrong (the user's words, the
|
||||
//! last error or the crash's message) and, for a crash, where it happened. The user's home
|
||||
//! folder is shown as `~`. Only with **Share my session** does it also carry the commands that
|
||||
//! built the model (the replayable journal, which can name the user's files), and only with
|
||||
//! **Include the model** as well the model file. A session too long for the link (GitHub
|
||||
//! refuses long new-issue links) goes out as a file to attach and on the clipboard instead; the
|
||||
//! model file is always one to attach.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::crash::without_home;
|
||||
|
||||
/// The issue form.
|
||||
pub const ISSUE_URL: &str = "https://github.com/jyviko/fieldcraft/issues/new";
|
||||
/// The longest link a draft opens: GitHub refuses new-issue links much past 8 KB.
|
||||
pub const MAX_URL: usize = 7000;
|
||||
/// The session file a draft attaches.
|
||||
pub const SESSION_FILE: &str = "fieldcraft-session.json";
|
||||
/// The model file a draft attaches.
|
||||
pub const MODEL_FILE: &str = "model.fieldcraft";
|
||||
/// Backtrace frames a crash's draft quotes.
|
||||
const FRAMES: usize = 12;
|
||||
/// A field's text is cut at this many bytes.
|
||||
const MAX_FIELD: usize = 3000;
|
||||
|
||||
/// What to put in a draft.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Input {
|
||||
pub title: String,
|
||||
/// What happened: the user's words, or the last error.
|
||||
pub observed: String,
|
||||
/// A crash report (`crash::read`), when reporting one.
|
||||
pub crash: Option<Value>,
|
||||
/// Attach the replayable commands.
|
||||
pub share_session: bool,
|
||||
/// The commands (each `{command, params}`) that rebuild the model from `model` (or from an
|
||||
/// empty model when there is none).
|
||||
pub commands: Vec<Value>,
|
||||
/// Attach the model file too (only with `share_session`).
|
||||
pub include_model: bool,
|
||||
pub model: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// A file the user attaches to the issue.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Attachment {
|
||||
pub name: String,
|
||||
pub bytes: Vec<u8>,
|
||||
/// What it is, for the review.
|
||||
pub what: String,
|
||||
}
|
||||
|
||||
/// A draft ready for review.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Draft {
|
||||
pub title: String,
|
||||
/// The bug form's fields by id (`observed`, `reproduction`, `evidence`, `version`), as the
|
||||
/// link fills them.
|
||||
pub fields: Vec<(&'static str, String)>,
|
||||
/// The link that opens the filled form.
|
||||
pub url: String,
|
||||
/// Files to attach (the session when too long for the link, the model).
|
||||
pub attachments: Vec<Attachment>,
|
||||
/// Text to put on the clipboard (the session, when it is an attachment).
|
||||
pub clipboard: Option<String>,
|
||||
}
|
||||
|
||||
impl Draft {
|
||||
/// The draft as JSON (attachments by name, size and what they are).
|
||||
pub fn to_json(&self) -> Value {
|
||||
json!({
|
||||
"title": self.title,
|
||||
"fields": self.fields.iter().map(|(k, v)| (k.to_string(), json!(v))).collect::<serde_json::Map<String, Value>>(),
|
||||
"url": self.url,
|
||||
"attachments": self.attachments.iter().map(|a| json!({"name": a.name, "bytes": a.bytes.len(), "what": a.what})).collect::<Vec<_>>(),
|
||||
"clipboard": self.clipboard.as_ref().map(String::len),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// `v0.5.8 (abc1234), macos aarch64`.
|
||||
pub fn version_line(version: &str, commit: &str) -> String {
|
||||
let commit = if commit.is_empty() { String::new() } else { format!(" ({commit})") };
|
||||
format!("v{version}{commit}, {} {}", std::env::consts::OS, std::env::consts::ARCH)
|
||||
}
|
||||
|
||||
/// Percent-encode `s` for a query value (RFC 3986 unreserved characters stay).
|
||||
pub fn encode(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for b in s.bytes() {
|
||||
if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
|
||||
out.push(char::from(b));
|
||||
} else {
|
||||
out.push_str(&format!("%{b:02X}"));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn cut(s: &str, n: usize) -> String {
|
||||
if s.len() <= n {
|
||||
return s.to_string();
|
||||
}
|
||||
let mut end = n;
|
||||
while !s.is_char_boundary(end) {
|
||||
end -= 1;
|
||||
}
|
||||
format!("{}\n[cut: {} bytes in all]", s.get(..end).unwrap_or_default(), s.len())
|
||||
}
|
||||
|
||||
fn link(title: &str, fields: &[(&'static str, String)]) -> String {
|
||||
let mut url = format!("{ISSUE_URL}?template=bug.yml&title={}", encode(title));
|
||||
for (k, v) in fields {
|
||||
if !v.is_empty() {
|
||||
url.push_str(&format!("&{k}={}", encode(v)));
|
||||
}
|
||||
}
|
||||
url
|
||||
}
|
||||
|
||||
/// What a crash report says, for the evidence field: its kind, message, place, command (its id;
|
||||
/// its parameters only with the session) and the top of its backtrace.
|
||||
fn crash_evidence(report: &Value, share: bool) -> String {
|
||||
let s = |k: &str| report.get(k).and_then(Value::as_str).unwrap_or("?");
|
||||
let mut out =
|
||||
format!("Crash report `{}` ({}), seen {} time(s)\n\n", s("id"), s("kind"), report.get("count").and_then(Value::as_u64).unwrap_or(1));
|
||||
out.push_str(&format!("Message: {}\nAt: {}\n", without_home(s("message")), without_home(s("location"))));
|
||||
if let Some(c) = report.get("command").filter(|c| !c.is_null()) {
|
||||
let id = c.get("command").and_then(Value::as_str).unwrap_or("?");
|
||||
match c.get("params").filter(|_| share) {
|
||||
Some(p) => out.push_str(&format!("Command: `{id}` {}\n", without_home(&p.to_string()))),
|
||||
None => out.push_str(&format!("Command: `{id}`\n")),
|
||||
}
|
||||
}
|
||||
if let Some(a) = report.get("last_activity").and_then(Value::as_str) {
|
||||
out.push_str(&format!("Last activity: {a}\n"));
|
||||
}
|
||||
let frames: Vec<&str> = report.get("backtrace").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).take(FRAMES).collect();
|
||||
if !frames.is_empty() {
|
||||
out.push_str("\nBacktrace (top):\n```\n");
|
||||
for f in frames {
|
||||
out.push_str(&without_home(f));
|
||||
out.push('\n');
|
||||
}
|
||||
out.push_str("```\n");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The draft for `input`, by the [`version_line`] `version`.
|
||||
pub fn draft(input: &Input, version: &str) -> Draft {
|
||||
let crash = input.crash.as_ref();
|
||||
let mut title = input.title.trim().to_string();
|
||||
if title.is_empty() {
|
||||
title = match crash.and_then(|c| c.get("kind")).and_then(Value::as_str) {
|
||||
Some("unclean_exit") => "FieldCraft closed unexpectedly".to_string(),
|
||||
Some(_) => "Internal error".to_string(),
|
||||
None => match input.observed.trim().lines().next().filter(|l| !l.is_empty()) {
|
||||
Some(line) => format!("Bug: {}", line.chars().take(100).collect::<String>()),
|
||||
None => "Bug report".to_string(),
|
||||
},
|
||||
};
|
||||
if let Some(c) = crash.and_then(|c| c.get("command")).and_then(|c| c.get("command")).and_then(Value::as_str) {
|
||||
title.push_str(&format!(" in {c}"));
|
||||
}
|
||||
}
|
||||
let title = cut(&without_home(&title), 200);
|
||||
let mut observed = without_home(input.observed.trim());
|
||||
if observed.is_empty()
|
||||
&& let Some(m) = crash.and_then(|c| c.get("message")).and_then(Value::as_str)
|
||||
{
|
||||
observed = without_home(m);
|
||||
}
|
||||
let observed = cut(&observed, MAX_FIELD);
|
||||
let share = input.share_session;
|
||||
let mut evidence = crash.map(|c| crash_evidence(c, share)).unwrap_or_default();
|
||||
let mut attachments = Vec::new();
|
||||
let mut clipboard = None;
|
||||
let mut reproduction = String::new();
|
||||
// The session: the replayable script, from the attached model when there is one.
|
||||
let model = input.model.as_ref().filter(|_| share && input.include_model);
|
||||
let script = share.then(|| {
|
||||
let mut steps = Vec::new();
|
||||
if model.is_some() {
|
||||
steps.push(json!({"command": "file.open", "params": {"path": MODEL_FILE}}));
|
||||
}
|
||||
steps.extend(input.commands.iter().cloned());
|
||||
Value::Array(steps)
|
||||
});
|
||||
if let Some(m) = model {
|
||||
attachments.push(Attachment { name: MODEL_FILE.into(), bytes: m.clone(), what: format!("the model ({} KB)", m.len().div_ceil(1024)) });
|
||||
}
|
||||
if let Some(script) = &script {
|
||||
let n = script.as_array().map_or(0, Vec::len);
|
||||
reproduction = format!("Replay the attached session ({n} command(s)): `fieldcraft-cli run {SESSION_FILE}`");
|
||||
if model.is_some() {
|
||||
reproduction.push_str(&format!(" in a folder holding `{MODEL_FILE}` too"));
|
||||
} else if crash.is_some_and(|c| c.get("files").and_then(|f| f.get("model")).is_some()) {
|
||||
reproduction.push_str(" (the crash replays from the model, which is not attached)");
|
||||
}
|
||||
reproduction.push('.');
|
||||
}
|
||||
let inline = |evidence: &str, script: &Value| {
|
||||
let text = serde_json::to_string_pretty(script).unwrap_or_default();
|
||||
format!("{evidence}\nSession ({SESSION_FILE}):\n```json\n{text}\n```\n")
|
||||
};
|
||||
let fields = |evidence: String| {
|
||||
vec![("observed", observed.clone()), ("reproduction", reproduction.clone()), ("evidence", evidence), ("version", version.to_string())]
|
||||
};
|
||||
// The session in the link when it fits, else a file to attach (also on the clipboard).
|
||||
let mut url = String::new();
|
||||
if let Some(script) = &script {
|
||||
let candidate = fields(inline(&evidence, script));
|
||||
let u = link(&title, &candidate);
|
||||
if u.len() <= MAX_URL {
|
||||
evidence = inline(&evidence, script);
|
||||
url = u;
|
||||
} else {
|
||||
let text = serde_json::to_string_pretty(script).unwrap_or_default();
|
||||
evidence.push_str(&format!(
|
||||
"\nThe session is too long for this form: FieldCraft saved it as `{SESSION_FILE}` and copied it to the clipboard. Attach the file here (drag it in) or paste it.\n"
|
||||
));
|
||||
attachments.insert(0, Attachment { name: SESSION_FILE.into(), bytes: text.clone().into_bytes(), what: "the session's commands".into() });
|
||||
clipboard = Some(text);
|
||||
}
|
||||
}
|
||||
if model.is_some() {
|
||||
evidence.push_str(&format!("\nThe model is attached as `{MODEL_FILE}` (drag it in from the folder FieldCraft saved it to).\n"));
|
||||
}
|
||||
if url.is_empty() || model.is_some() {
|
||||
let mut f = fields(evidence.clone());
|
||||
url = link(&title, &f);
|
||||
// Still too long (a very long message): cut the longest field until it fits.
|
||||
while url.len() > MAX_URL {
|
||||
let Some((i, len)) = f.iter().enumerate().map(|(i, (_, v))| (i, v.len())).max_by_key(|(_, l)| *l) else { break };
|
||||
if len < 200 {
|
||||
break;
|
||||
}
|
||||
if let Some((_, v)) = f.get_mut(i) {
|
||||
*v = cut(v, len.saturating_sub(url.len() - MAX_URL + 64).min(len / 2 + 1));
|
||||
}
|
||||
url = link(&title, &f);
|
||||
}
|
||||
evidence = f.get(2).map(|(_, v)| v.clone()).unwrap_or_default();
|
||||
}
|
||||
let fields = fields(evidence);
|
||||
// The fields as the link carries them (a cut field included).
|
||||
let fields = if url == link(&title, &fields) { fields } else { decode_fields(&url) };
|
||||
Draft { title, fields, url, attachments, clipboard }
|
||||
}
|
||||
|
||||
/// Write a draft's attachments to `bug-reports/<time>/` in the app's data folder (the user
|
||||
/// attaches them from there); returns the folder.
|
||||
pub fn save_attachments(draft: &Draft) -> Result<std::path::PathBuf, String> {
|
||||
let root = fieldcraft_io::recovery::data_dir().ok_or("no data folder on this system")?;
|
||||
let dir = root.join("bug-reports").join(crate::crash::stamp_now());
|
||||
fieldcraft_io::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
|
||||
for a in &draft.attachments {
|
||||
fieldcraft_io::fs::write_atomic(&dir.join(&a.name), &a.bytes, false).map_err(|e| e.to_string())?;
|
||||
}
|
||||
Ok(dir)
|
||||
}
|
||||
|
||||
/// The fields a link carries (for the review, when a field had to be cut).
|
||||
fn decode_fields(url: &str) -> Vec<(&'static str, String)> {
|
||||
let query = url.split_once('?').map_or("", |(_, q)| q);
|
||||
["observed", "reproduction", "evidence", "version"]
|
||||
.into_iter()
|
||||
.map(|k| {
|
||||
let v = query.split('&').find_map(|kv| kv.strip_prefix(k).and_then(|r| r.strip_prefix('='))).unwrap_or_default();
|
||||
(k, decode(v))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn decode(s: &str) -> String {
|
||||
let b = s.as_bytes();
|
||||
let mut out = Vec::with_capacity(b.len());
|
||||
let mut i = 0;
|
||||
while let Some(&c) = b.get(i) {
|
||||
let hex = b.get(i + 1..i + 3).and_then(|h| std::str::from_utf8(h).ok()).and_then(|h| u8::from_str_radix(h, 16).ok());
|
||||
match (c, hex) {
|
||||
(b'%', Some(v)) => {
|
||||
out.push(v);
|
||||
i += 3;
|
||||
}
|
||||
_ => {
|
||||
out.push(c);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
String::from_utf8_lossy(&out).into_owned()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn home() -> String {
|
||||
std::env::var("HOME").or_else(|_| std::env::var("USERPROFILE")).unwrap_or_else(|_| "/home/someone".into())
|
||||
}
|
||||
|
||||
fn crash() -> Value {
|
||||
json!({
|
||||
"id": "20261014-101500-00000000deadbeef", "kind": "command_panic", "count": 2,
|
||||
"message": format!("index out of bounds in {}/model.fieldcraft", home()),
|
||||
"location": "crates/mesh/src/tet.rs:42",
|
||||
"command": {"command": "mesh.tet.generate", "params": {"body": "Plate", "path": format!("{}/secret/plate.step", home())}},
|
||||
"backtrace": ["fieldcraft_mesh::tet::insert (crates/mesh/src/tet.rs:42)"],
|
||||
"files": {"model": "model.fieldcraft", "replay": "replay.json"},
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_sharing_a_draft_names_no_paths_commands_or_model() {
|
||||
let input = Input {
|
||||
observed: format!("cannot open {}/parts/bracket.solidcraft", home()),
|
||||
crash: Some(crash()),
|
||||
commands: vec![json!({"command": "geometry.open", "params": {"path": format!("{}/parts/bracket.solidcraft", home())}})],
|
||||
model: Some(b"model bytes".to_vec()),
|
||||
include_model: true,
|
||||
..Default::default()
|
||||
};
|
||||
let d = draft(&input, "v1.2.3, testos x");
|
||||
assert!(d.url.starts_with("https://github.com/jyviko/fieldcraft/issues/new?template=bug.yml&title="), "{}", d.url);
|
||||
assert!(d.attachments.is_empty() && d.clipboard.is_none(), "nothing attached without Share my session");
|
||||
let all = format!("{} {:?} {}", d.title, d.fields, decode(&d.url));
|
||||
assert!(!all.contains(&home()), "no home folder: {all}");
|
||||
assert!(!all.contains("secret") && !all.contains("geometry.open"), "no parameters or commands: {all}");
|
||||
assert!(all.contains("~/parts/bracket.solidcraft"), "the error, its home shown as ~: {all}");
|
||||
assert!(all.contains("mesh.tet.generate") && all.contains("tet.rs:42") && all.contains("v1.2.3, testos x"), "{all}");
|
||||
assert_eq!(d.title, "Internal error in mesh.tet.generate");
|
||||
assert_eq!(decode_fields(&d.url), d.fields, "the review shows what the link carries");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_short_session_goes_in_the_link() {
|
||||
let input = Input {
|
||||
title: "Solve fails".into(),
|
||||
share_session: true,
|
||||
commands: vec![json!({"command": "file.sample", "params": {"name": "cantilever"}}), json!({"command": "solve.run", "params": {}})],
|
||||
..Default::default()
|
||||
};
|
||||
let d = draft(&input, "v1");
|
||||
assert!(d.attachments.is_empty() && d.clipboard.is_none());
|
||||
let evidence = &d.fields.iter().find(|(k, _)| *k == "evidence").unwrap().1;
|
||||
assert!(evidence.contains("\"command\": \"solve.run\""), "{evidence}");
|
||||
assert!(d.url.len() <= MAX_URL);
|
||||
assert!(decode(&d.url).contains("file.sample"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_session_and_the_model_are_attachments() {
|
||||
let commands: Vec<Value> = (0..400).map(|i| json!({"command": "mesh.node.add", "params": {"label": i + 1, "xyz": [i, 0, 0]}})).collect();
|
||||
let input =
|
||||
Input { share_session: true, include_model: true, commands, model: Some(vec![7; 3000]), crash: Some(crash()), ..Default::default() };
|
||||
let d = draft(&input, "v1");
|
||||
assert!(d.url.len() <= MAX_URL, "{}", d.url.len());
|
||||
let names: Vec<&str> = d.attachments.iter().map(|a| a.name.as_str()).collect();
|
||||
assert_eq!(names, [SESSION_FILE, MODEL_FILE]);
|
||||
let session: Value = serde_json::from_slice(&d.attachments[0].bytes).unwrap();
|
||||
assert_eq!(session[0], json!({"command": "file.open", "params": {"path": MODEL_FILE}}), "the replay opens the attached model");
|
||||
assert_eq!(session.as_array().unwrap().len(), 401);
|
||||
assert_eq!(d.clipboard.as_deref().map(str::as_bytes), Some(d.attachments[0].bytes.as_slice()));
|
||||
let text = decode(&d.url);
|
||||
assert!(text.contains("too long for this form") && text.contains(MODEL_FILE) && !text.contains("\"label\": 399"), "{text}");
|
||||
// With the session shared, the crash's command parameters are shown (home as ~).
|
||||
assert!(text.contains("~/secret/plate.step"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_huge_message_is_cut_to_fit_the_link() {
|
||||
let input = Input { observed: "é".repeat(20_000), ..Default::default() };
|
||||
let d = draft(&input, "v1");
|
||||
assert!(d.url.len() <= MAX_URL, "{}", d.url.len());
|
||||
assert!(d.fields[0].1.contains("[cut:"));
|
||||
assert_eq!(decode_fields(&d.url), d.fields);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoding_round_trips() {
|
||||
let s = "a b&c=d/é\n```json";
|
||||
assert_eq!(decode(&encode(s)), s);
|
||||
assert_eq!(encode("a b&"), "a%20b%26");
|
||||
}
|
||||
}
|
||||
@@ -155,6 +155,10 @@ pub struct Capability {
|
||||
pub status: Status,
|
||||
/// Related commands in the entry's drop-down (edit, delete…).
|
||||
pub more: &'static [&'static str],
|
||||
/// Commands the entry's own form covers (an option of it does the same), or that act on what
|
||||
/// it makes from the browser's item menu (edit, delete): claimed by the entry for the command
|
||||
/// search and the ribbon's stage, but not listed in the ribbon.
|
||||
pub covers: &'static [&'static str],
|
||||
}
|
||||
|
||||
impl Capability {
|
||||
@@ -194,7 +198,7 @@ impl Capability {
|
||||
}
|
||||
|
||||
const fn ready(id: &'static str, label: &'static str, tab: Tab, panel: &'static str, tip: &'static str) -> Capability {
|
||||
Capability { id, label, tab, panel, tip, status: Status::Ready, more: &[] }
|
||||
Capability { id, label, tab, panel, tip, status: Status::Ready, more: &[], covers: &[] }
|
||||
}
|
||||
|
||||
const fn ready_more(
|
||||
@@ -208,12 +212,23 @@ const fn ready_more(
|
||||
Capability { more, ..ready(id, label, tab, panel, tip) }
|
||||
}
|
||||
|
||||
const fn covering(
|
||||
id: &'static str,
|
||||
label: &'static str,
|
||||
tab: Tab,
|
||||
panel: &'static str,
|
||||
tip: &'static str,
|
||||
covers: &'static [&'static str],
|
||||
) -> Capability {
|
||||
Capability { covers, ..ready(id, label, tab, panel, tip) }
|
||||
}
|
||||
|
||||
const fn soon(id: &'static str, label: &'static str, tab: Tab, panel: &'static str, milestone: &'static str, tip: &'static str) -> Capability {
|
||||
Capability { id, label, tab, panel, tip, status: Status::Planned { milestone }, more: &[] }
|
||||
Capability { id, label, tab, panel, tip, status: Status::Planned { milestone }, more: &[], covers: &[] }
|
||||
}
|
||||
|
||||
const fn deck(id: &'static str, label: &'static str, format: &'static str, tip: &'static str) -> Capability {
|
||||
Capability { id, label, tab: Tab::Solve, panel: "Decks", tip, status: Status::Deck { format, milestone: "M3" }, more: &[] }
|
||||
Capability { id, label, tab: Tab::Solve, panel: "Decks", tip, status: Status::Deck { format, milestone: "M3" }, more: &[], covers: &[] }
|
||||
}
|
||||
|
||||
use Tab::*;
|
||||
@@ -232,12 +247,50 @@ pub static CATALOGUE: &[Capability] = &[
|
||||
"Inspect",
|
||||
"Weld, closed, manifold, orientation and self-intersection checks; feature edges",
|
||||
),
|
||||
soon("geometry.partition", "Partition", Geometry, "Prepare", "M5", "Split bodies and faces as SolidCraft features"),
|
||||
soon("geometry.datum", "Datum Plane", Geometry, "Prepare", "M5", "Construction planes for partitions"),
|
||||
// Edit and delete of datums and partitions are on the browser's item menu, not the ribbon.
|
||||
covering(
|
||||
"geometry.datum",
|
||||
"Datum Plane",
|
||||
Geometry,
|
||||
"Prepare",
|
||||
"A datum plane: principal plane and offset, three points or datum points, point and normal, normal to an axis",
|
||||
&["geometry.datum.edit", "geometry.datum.delete"],
|
||||
),
|
||||
covering(
|
||||
"geometry.datum.axis",
|
||||
"Datum Axis",
|
||||
Geometry,
|
||||
"Prepare",
|
||||
"A datum axis: principal axis, two points or datum points, point and direction",
|
||||
&["geometry.datum.axis.edit"],
|
||||
),
|
||||
covering(
|
||||
"geometry.datum.point",
|
||||
"Datum Point",
|
||||
Geometry,
|
||||
"Prepare",
|
||||
"A datum point: coordinates, a mesh vertex, along an edge, a face's centre, an axis through a plane",
|
||||
&["geometry.datum.point.edit"],
|
||||
),
|
||||
covering(
|
||||
"geometry.partition",
|
||||
"Partition",
|
||||
Geometry,
|
||||
"Prepare",
|
||||
"Cut bodies into cells by a datum plane; the two faces of each cut are paired by name",
|
||||
&["geometry.partition.delete"],
|
||||
),
|
||||
soon("geometry.midsurface", "Midsurface", Geometry, "Prepare", "M8", "Extract midsurfaces of thin parts for shell meshes"),
|
||||
// ---- Mesh ----
|
||||
soon("mesh.size.global", "Global Size", Mesh, "Size", "M2", "One element size for the whole part"),
|
||||
soon("mesh.size.seed", "Seed Edges", Mesh, "Size", "M2", "Element counts, sizes and bias per edge and face"),
|
||||
ready_more(
|
||||
"mesh.seed.edge",
|
||||
"Seed Edges",
|
||||
Mesh,
|
||||
"Size",
|
||||
"Element counts or sizes per design edge, with bias and an exact, minimum or free constraint; the meshers honour them",
|
||||
&["mesh.seed.clear", "mesh.seed.list"],
|
||||
),
|
||||
soon("mesh.size.adapt", "Curvature", Mesh, "Size", "M2", "Refine by curvature and proximity"),
|
||||
ready(
|
||||
"mesh.tet.generate",
|
||||
@@ -256,30 +309,30 @@ pub static CATALOGUE: &[Capability] = &[
|
||||
"Quad or triangle mesh of a planar face or polygon in the XY plane for plane stress, plane strain and axisymmetric models; edges tagged",
|
||||
),
|
||||
soon("mesh.quad.faces", "Quad Faces", Mesh, "Structured Hex", "M5", "All-quad meshes of faces on shared edge nodes"),
|
||||
ready_more(
|
||||
"mesh.hex.mapped",
|
||||
"Mapped Hex",
|
||||
covering(
|
||||
"mesh.hex.generate",
|
||||
"Hex Mesh",
|
||||
Mesh,
|
||||
"Structured Hex",
|
||||
"Mapped hex mesh of a six-sided block (curved faces allowed)",
|
||||
&["mesh.hex.generate"],
|
||||
"Structured hex mesh of a body: automatic, or extruded, swept, revolved or mapped (the Method drop-down)",
|
||||
&["mesh.hex.sweep", "mesh.hex.mapped"],
|
||||
),
|
||||
ready_more(
|
||||
"mesh.hex.sweep",
|
||||
"Sweep Hex",
|
||||
covering(
|
||||
"mesh.cells",
|
||||
"Partitioned Mesh",
|
||||
Mesh,
|
||||
"Structured Hex",
|
||||
"Hex mesh swept along extrusions (several levels), around revolutions, or from a source face to a target",
|
||||
&["mesh.hex.generate"],
|
||||
"One mesh of a partitioned part, a method per cell (hex, tet, or all hex as conforming blocks); cells joined across partitions",
|
||||
&["mesh.hex.blocks"],
|
||||
),
|
||||
ready(
|
||||
"mesh.hex.blocks",
|
||||
"Block Hex",
|
||||
soon(
|
||||
"mesh.hex.decompose",
|
||||
"Decompose",
|
||||
Mesh,
|
||||
"Structured Hex",
|
||||
"One conforming hex mesh of a part split into six-sided blocks: shared faces meshed once",
|
||||
"M5",
|
||||
"Find sweepable and mappable regions of 3D parts (extruded cross-sections are already cut into blocks by Hex Mesh)",
|
||||
),
|
||||
soon("mesh.hex.decompose", "Decompose", Mesh, "Structured Hex", "M5", "Find sweepable and mappable regions and propose the splits"),
|
||||
soon("mesh.transition", "Transition", Mesh, "Structured Hex", "M5", "Conforming tet–hex interfaces with pyramids"),
|
||||
ready(
|
||||
"mesh.hex.octree",
|
||||
@@ -300,7 +353,7 @@ pub static CATALOGUE: &[Capability] = &[
|
||||
Mesh,
|
||||
"Edit",
|
||||
"Add an element on existing nodes, or a mapped block of them",
|
||||
&["mesh.element.remove", "mesh.block"],
|
||||
&["mesh.element.remove", "mesh.block", "mesh.mirror"],
|
||||
),
|
||||
soon("mesh.node.merge", "Merge Nodes", Mesh, "Edit", "M6", "Merge coincident nodes"),
|
||||
soon("mesh.region.remesh", "Remesh Region", Mesh, "Edit", "M6", "Remesh a region in place; split and collapse elements"),
|
||||
@@ -372,7 +425,7 @@ pub static CATALOGUE: &[Capability] = &[
|
||||
Loads,
|
||||
"Boundary Conditions",
|
||||
"Fixed, displacement or symmetry condition on a set or reference point",
|
||||
&["model.boundary_condition.edit", "model.boundary_condition.delete"],
|
||||
&["model.boundary_condition.edit", "model.boundary_condition.delete", "model.boundary_condition.symmetry"],
|
||||
),
|
||||
ready_more(
|
||||
"model.load.create",
|
||||
@@ -430,13 +483,13 @@ pub static CATALOGUE: &[Capability] = &[
|
||||
"Contact between everything that may touch, or self contact of a surface, with friction (explicit dynamics and nonlinear static steps)",
|
||||
&["interaction.contact.edit", "interaction.contact.delete"],
|
||||
),
|
||||
ready_more(
|
||||
// Its edit and delete rows are General Contact's: they act on contacts of either kind.
|
||||
ready(
|
||||
"interaction.contact.pair",
|
||||
"Contact Pair",
|
||||
Interactions,
|
||||
"Contact",
|
||||
"Contact between two surfaces: with friction in explicit dynamics, mortar contact with friction in nonlinear static steps",
|
||||
&["interaction.contact.edit", "interaction.contact.delete"],
|
||||
),
|
||||
ready(
|
||||
"interaction.contact.find",
|
||||
@@ -534,8 +587,25 @@ pub static CATALOGUE: &[Capability] = &[
|
||||
"Open a model autosaved by an app that crashed or closed with unsaved changes",
|
||||
&["file.recovery.list", "file.recovery.discard"],
|
||||
),
|
||||
// Hide, show and isolate act on the browser's items, from their eyes and item menus.
|
||||
covering(
|
||||
"view.show_all",
|
||||
"Show All",
|
||||
Tools,
|
||||
"View",
|
||||
"Show every item hidden in the viewport (hide, show and isolate items from the browser)",
|
||||
&["view.hide", "view.show", "view.isolate"],
|
||||
),
|
||||
ready("edit.undo", "Undo", Tools, "History", "Undo the last command that changed the model"),
|
||||
ready("edit.redo", "Redo", Tools, "History", "Redo the command undone last"),
|
||||
ready_more(
|
||||
"diagnostics.bug_report",
|
||||
"Report a Bug",
|
||||
Tools,
|
||||
"Help",
|
||||
"Draft a GitHub bug report with the version, the OS and the last error; you review it, and nothing is sent until you submit it",
|
||||
&["diagnostics.crash_reports", "diagnostics.crash_report", "diagnostics.crash_test", "app.update.check"],
|
||||
),
|
||||
];
|
||||
|
||||
/// The catalogue entry with this id.
|
||||
@@ -544,9 +614,12 @@ pub fn find(id: &str) -> Option<&'static Capability> {
|
||||
}
|
||||
|
||||
/// The entry that claims a command: the one running it, else the one listing it among its
|
||||
/// related commands. Every registered command has one (a test checks it).
|
||||
/// related commands or covering it. Every registered command has one (a test checks it).
|
||||
pub fn entry_of(command: &str) -> Option<&'static Capability> {
|
||||
CATALOGUE.iter().find(|c| c.command() == Some(command)).or_else(|| CATALOGUE.iter().find(|c| c.more.contains(&command)))
|
||||
CATALOGUE
|
||||
.iter()
|
||||
.find(|c| c.command() == Some(command))
|
||||
.or_else(|| CATALOGUE.iter().find(|c| c.more.contains(&command) || c.covers.contains(&command)))
|
||||
}
|
||||
|
||||
/// The tab the ribbon follows to when `command` has run from anywhere but the ribbon (a script,
|
||||
@@ -589,7 +662,8 @@ pub fn features_page() -> String {
|
||||
let preset = c.preset();
|
||||
let main =
|
||||
c.command().map(|id| if preset.as_object().is_some_and(|o| !o.is_empty()) { format!("`{id} {preset}`") } else { format!("`{id}`") });
|
||||
let commands: Vec<String> = main.into_iter().chain(c.more.iter().map(|id| format!("`{id}`"))).collect();
|
||||
let commands: Vec<String> =
|
||||
main.into_iter().chain(c.more.iter().map(|id| format!("`{id}`"))).chain(c.covers.iter().map(|id| format!("(`{id}`)"))).collect();
|
||||
let _ = writeln!(md, "| {} | {} — {} | {status} | {} |", c.panel, c.label, c.tip, commands.join(", "));
|
||||
}
|
||||
}
|
||||
@@ -619,6 +693,25 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Each command has one place in the ribbon: no two menu rows (an entry or a drop-down row)
|
||||
/// run the same command with the same preset, and a command an entry's form covers is no row.
|
||||
#[test]
|
||||
fn no_command_appears_twice_across_ribbon_menus() {
|
||||
let mut rows: Vec<String> = Vec::new();
|
||||
for c in CATALOGUE {
|
||||
let entry = c.command().map(|id| format!("{id} {}", c.preset()));
|
||||
for row in entry.into_iter().chain(c.more.iter().map(|id| format!("{id} {{}}"))) {
|
||||
assert!(!rows.contains(&row), "{}: `{row}` is in the ribbon twice", c.id);
|
||||
rows.push(row);
|
||||
}
|
||||
}
|
||||
for c in CATALOGUE {
|
||||
for m in c.covers {
|
||||
assert!(!rows.iter().any(|r| r.split(' ').next() == Some(m)), "{}: `{m}` is covered by its form and also a ribbon row", c.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_ribbon_follows_each_command_to_its_stage() {
|
||||
assert_eq!(stage_tab("mesh.hex.sweep"), Some(Tab::Mesh));
|
||||
@@ -633,7 +726,7 @@ mod tests {
|
||||
assert_eq!(stage_tab("no.such"), None);
|
||||
// A ribbon click (an entry's command, or one of its drop-down's) stays on the tab shown.
|
||||
for c in CATALOGUE {
|
||||
for command in c.command().into_iter().chain(c.more.iter().copied()) {
|
||||
for command in c.command().into_iter().chain(c.more.iter().copied()).chain(c.covers.iter().copied()) {
|
||||
assert!(stage_tab(command).is_none_or(|t| t == c.tab), "{}: `{command}` would move the ribbon from {:?}", c.id, c.tab);
|
||||
}
|
||||
}
|
||||
@@ -647,9 +740,9 @@ mod tests {
|
||||
assert!(find_command(command).is_some(), "{}: `{command}` is not a registered command", c.id);
|
||||
claimed.push(command);
|
||||
} else {
|
||||
assert!(c.more.is_empty(), "{}: a planned entry has no commands", c.id);
|
||||
assert!(c.more.is_empty() && c.covers.is_empty(), "{}: a planned entry has no commands", c.id);
|
||||
}
|
||||
for m in c.more {
|
||||
for m in c.more.iter().chain(c.covers) {
|
||||
assert!(find_command(m).is_some(), "{}: `{m}` is not a registered command", c.id);
|
||||
claimed.push(m);
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ pub const BLOCK: CommandSpec = CommandSpec {
|
||||
params: r#"{"body": "Plate", "kind": "hex8|hex20|tet4|tet10|wedge6", "corners": [[x, y, z] × 8] (hex8 order: 1-2-3-4 counter-clockwise seen from 5-6-7-8), "divisions": [n12, n14, n15] (elements along 1→2, 1→4, 1→5), "bias": [1, 1, 1] (optional: last over first element size along each direction), "edges": [{"corners": [1, 2], "arc": {"center": [x, y, z]}} | {"corners": [2, 3], "ellipse": {"center": [x, y, z], "axes": [[a], [b]] (perpendicular)}} | {"corners": [5, 6], "name": "tip_edge"}] (optional: curved edges, the shorter arc between the corners, and edge names), "faces": {"1": "bottom", "4": "tip"} (optional: names of block faces, numbered as hex8 faces: 1 = 1-2-3-4, 2 = 5-6-7-8, 3 = 1-2-6-5, 4 = 2-3-7-6, 5 = 3-4-8-7, 6 = 4-1-5-8), "vertices": {"1": "A"} (optional: names of corners), "merge": distance (optional, default 1e-6 of the block's diagonal; 0 never joins)} — adds a mapped mesh of the block (transfinite interpolation of its edges; quadratic nodes on the curves), uses existing nodes within `merge` of new ones so blocks that share a face join (the shared face must have the same elements on both sides, or nothing changes), and tags the elements with the body and element faces, edges and nodes with the named faces, edges and vertices. 2D: "kind": "quad4|quad8|tri3|tri6", four "corners" at z = 0 (counter-clockwise from +z), "divisions": [n12, n14], "bias": [r, r], "face": "area" (the face of the body the elements fill, default `area`), edges and vertices numbered among the four corners; for plane stress, plane strain and axisymmetric sections"#,
|
||||
form: Some(super::forms::BLOCK),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[],
|
||||
run: block_mesh,
|
||||
};
|
||||
|
||||
@@ -108,7 +109,7 @@ fn block_mesh(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let region = match (planar, &p.face) {
|
||||
(true, face) => GeometryRef::face(p.body.clone(), face.clone().unwrap_or_else(|| "area".into()))?,
|
||||
(false, None) => GeometryRef::body(p.body.clone())?,
|
||||
(false, Some(_)) => return Err(EngineError::Params("`face` names the region of 2D elements; a solid block fills its body".into())),
|
||||
(false, Some(_)) => return Err(EngineError::invalid("face", "names the region of 2D elements; a solid block fills its body")),
|
||||
};
|
||||
if planar && !p.faces.is_empty() {
|
||||
return Err(EngineError::Params("a 2D patch has no faces to name: name its edges".into()));
|
||||
|
||||
@@ -0,0 +1,494 @@
|
||||
//! Meshing a partitioned part cell by cell (`mesh.cells`): each cell (a body of the open design,
|
||||
//! typically made by `geometry.partition`) with its own method, all into one mesh, and the cells
|
||||
//! joined across the partitions that divide them.
|
||||
//!
|
||||
//! **Joining.** Two cells on either side of a partition `P` meet on faces named
|
||||
//! `partition:P:a` and `partition:P:b`. Where the element faces of the two sides match node for
|
||||
//! node (the same divisions and kind on both sides, e.g. a mesh and its mirror image) the
|
||||
//! coincident nodes are merged and the mesh is conforming there. Elsewhere — a hex cell next to a
|
||||
//! tet cell, or two cells meshed with different divisions — the two surfaces are tied: a set on
|
||||
//! each side's partition faces and a tie between them (`interaction.tie`; dual mortar
|
||||
//! constraints in the implicit analyses, so a constant stress crosses the interface exactly).
|
||||
//! The tie is the transition between hex and tet cells; pyramid elements are not used, because
|
||||
//! they need their own element formulation in every solver and deck, while the tie works for any
|
||||
//! pair of meshes and keeps each cell's mesh as its method made it. The reply lists every
|
||||
//! interface and how it was joined.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use fieldcraft_mesh::cdt::CdtOptions;
|
||||
use fieldcraft_mesh::hex::{HexMesh, HexMethod};
|
||||
use fieldcraft_model::geometry::Entity;
|
||||
use fieldcraft_model::{ElementFace, GeometryRef, Model, Set, Tie};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::hex::{Input, add_hex, hex_body};
|
||||
use super::mesh::{BodyTets, add_tets, mesh_body, quality_options};
|
||||
use crate::requirement::Requirement;
|
||||
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
|
||||
|
||||
pub const CELLS: CommandSpec = CommandSpec {
|
||||
id: "mesh.cells",
|
||||
label: "Partitioned Mesh",
|
||||
params: r#"{"methods": {"Body1/a": "tet", "Body1/b": "swept"} (per cell; default `default`), "default": "auto", "bodies": ["Body1/a", "Body1/b"] (default: every body of the open design), "size": 2.0 (element size, mm; default 1/25 of the bounding-box diagonal of all of them), "order": 1 | 2 (hex8 and tet4, or hex20 and tet10), "tolerance": 0.05 (chordal tolerance, mm)} — replaces the cells' meshes (as mesh.tet.generate; other bodies keep theirs) with one mesh of the cells, each with its method: "auto" (structured hex where a method fits, else tet), "hex" (any structured hex method), "swept", "extrude", "sweep", "revolve", "mapped" or "tet"; or "default": "blocks" (with no `methods`): every cell a mapped block, division counts assigned over all cells together, exactly mesh.hex.blocks with the same parameters. Cells on either side of a partition (faces `partition:<name>:a` and `:b`) are joined: where their element faces match node for node the nodes are merged (conforming); otherwise, as between a hex and a tet cell, a set on each side and a tie between them are made (`tie_<partition>_<k>`, sets `<tie>_main` and `<tie>_secondary`: the side with fewer nodes is the main surface), replacing ties of those names from an earlier run. Reports each cell's method (and why auto fell back to tet), and each interface: `merged` with the nodes merged, or `tied`"#,
|
||||
form: Some(super::forms::CELLS),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Design],
|
||||
run: cells,
|
||||
};
|
||||
|
||||
/// Distance (relative to the cells' bounding-box diagonal) within which interface nodes coincide.
|
||||
const COINCIDENT: f64 = 1e-7;
|
||||
|
||||
/// A cell's method.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Method {
|
||||
Auto,
|
||||
Hex(HexMethod),
|
||||
Tet,
|
||||
}
|
||||
|
||||
impl Method {
|
||||
fn parse(v: &Value) -> Result<Method> {
|
||||
let name = v.as_str().unwrap_or_default();
|
||||
Ok(match name {
|
||||
"auto" => Method::Auto,
|
||||
"hex" => Method::Hex(HexMethod::Auto),
|
||||
"tet" => Method::Tet,
|
||||
_ => match HexMethod::from_name(name).filter(|m| *m != HexMethod::Auto) {
|
||||
Some(m) => Method::Hex(m),
|
||||
None => {
|
||||
return Err(EngineError::Params(format!(
|
||||
"method `{}` is not one of auto, hex, swept, extrude, sweep, revolve, mapped, tet",
|
||||
name.chars().take(40).collect::<String>()
|
||||
)));
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A meshed cell.
|
||||
enum Meshed<'a> {
|
||||
Hex(Input<'a>, HexMesh),
|
||||
Tet(BodyTets),
|
||||
}
|
||||
|
||||
fn cells(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if p.get("default").and_then(Value::as_str) == Some("blocks") {
|
||||
if p.get("methods").is_some_and(|m| m.as_object().is_none_or(|o| !o.is_empty())) {
|
||||
return Err(EngineError::param(
|
||||
"methods",
|
||||
crate::schema::ProblemKind::Invalid("must be empty with \"default\": \"blocks\" (every cell a block)".into()),
|
||||
));
|
||||
}
|
||||
return super::hex::hex_blocks(s, p);
|
||||
}
|
||||
let size = super::hex::number(p, "size")?;
|
||||
let quadratic = match p.get("order") {
|
||||
None => false,
|
||||
Some(v) => match v.as_u64() {
|
||||
Some(1) => false,
|
||||
Some(2) => true,
|
||||
_ => return Err(EngineError::invalid("order", "must be 1 or 2")),
|
||||
},
|
||||
};
|
||||
let default = p.get("default").map(Method::parse).transpose()?.unwrap_or(Method::Auto);
|
||||
let methods: BTreeMap<String, Method> = match p.get("methods") {
|
||||
None => BTreeMap::new(),
|
||||
Some(Value::Object(m)) => m.iter().map(|(k, v)| Ok((k.clone(), Method::parse(v)?))).collect::<Result<_>>()?,
|
||||
Some(_) => return Err(EngineError::invalid("methods", "must map cell names to methods")),
|
||||
};
|
||||
let design = s.design.clone().ok_or_else(|| EngineError::Params("open a design first".into()))?;
|
||||
let names: Vec<String> = match p.get("bodies") {
|
||||
None => design.bodies.iter().map(|b| b.name.clone()).collect(),
|
||||
Some(_) => super::req(p, "bodies")?,
|
||||
};
|
||||
if names.is_empty() || names.len() > fieldcraft_mesh::hex::MAX_CELLS {
|
||||
return Err(EngineError::Params(format!("{} cells; mesh.cells meshes 1 to {}", names.len(), fieldcraft_mesh::hex::MAX_CELLS)));
|
||||
}
|
||||
for n in methods.keys() {
|
||||
if !names.contains(n) {
|
||||
return Err(EngineError::Params(format!("`methods` names `{n}`, which is not a cell being meshed")));
|
||||
}
|
||||
}
|
||||
// One size and tolerance from the cells' joint extent, as mesh.hex.blocks does.
|
||||
let (mut lo, mut hi) = ([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]);
|
||||
let mut shapes = Vec::with_capacity(names.len());
|
||||
for (i, n) in names.iter().enumerate() {
|
||||
if names.get(..i).is_some_and(|b| b.contains(n)) {
|
||||
return Err(EngineError::Params(format!("cell `{n}` is listed twice")));
|
||||
}
|
||||
let shape = design.body(n).ok_or_else(|| EngineError::Params(format!("no body `{n}`")))?;
|
||||
let m = shape.measure()?;
|
||||
for k in 0..3 {
|
||||
lo[k] = lo[k].min(m.bbox_min[k]);
|
||||
hi[k] = hi[k].max(m.bbox_max[k]);
|
||||
}
|
||||
shapes.push(shape);
|
||||
}
|
||||
let diagonal = (0..3).map(|k| (hi[k] - lo[k]).powi(2)).sum::<f64>().sqrt();
|
||||
if !(diagonal > 0.0 && diagonal.is_finite()) {
|
||||
return Err(EngineError::Params("the cells have no extent".into()));
|
||||
}
|
||||
let size = Some(size.unwrap_or(diagonal / 25.0));
|
||||
let tolerance = super::hex::number(p, "tolerance")?.unwrap_or(1e-3 * diagonal);
|
||||
// The tet mesher's parameters: the same size and tolerance, its own order names.
|
||||
let mut tet_params = json!({"size": size, "tolerance": tolerance, "order": if quadratic { "quadratic" } else { "linear" }});
|
||||
for key in ["weld", "weld_distance", "feature_angle"] {
|
||||
if let (Some(v), Some(o)) = (p.get(key), tet_params.as_object_mut()) {
|
||||
o.insert(key.into(), v.clone());
|
||||
}
|
||||
}
|
||||
let mut hex_params = tet_params.clone();
|
||||
if let Some(o) = hex_params.as_object_mut() {
|
||||
o.remove("order");
|
||||
}
|
||||
let (tet_options, quality) = quality_options(&tet_params, s.limits.max_tets as u64)?;
|
||||
let cdt = CdtOptions { max_steiner: s.limits.max_steiner, max_tets: tet_options.max_tets };
|
||||
|
||||
let seeds = super::seeds::edge_seeds(s)?;
|
||||
let mut meshed: Vec<(Meshed, Value)> = Vec::with_capacity(shapes.len());
|
||||
for shape in shapes {
|
||||
let method = methods.get(&shape.name).copied().unwrap_or(default);
|
||||
let input = || Ok::<_, EngineError>(Input { seeds: seeds.clone(), ..super::hex::shape_input(shape, Some(tolerance))? });
|
||||
let hex = |m: HexMethod| -> Result<(Input<'static>, HexMesh)> {
|
||||
let b = input()?;
|
||||
let mesh = hex_body(&hex_params, &b, m, quadratic, size)?;
|
||||
Ok((b, mesh))
|
||||
};
|
||||
let tet = |s: &Session| mesh_body(s, &tet_params, input()?, &cdt, &tet_options, quality, true);
|
||||
let (cell, mut info) = match method {
|
||||
Method::Hex(m) => {
|
||||
let (b, mesh) = hex(m)?;
|
||||
let info = json!({"method": mesh.report.method.name()});
|
||||
(Meshed::Hex(b, mesh), info)
|
||||
}
|
||||
Method::Tet => (Meshed::Tet(tet(s)?), json!({"method": "tet"})),
|
||||
Method::Auto => match hex(HexMethod::Auto) {
|
||||
Ok((b, mesh)) => {
|
||||
let info = json!({"method": mesh.report.method.name()});
|
||||
(Meshed::Hex(b, mesh), info)
|
||||
}
|
||||
Err(e) => (Meshed::Tet(tet(s)?), json!({"method": "tet", "why": e.to_string()})),
|
||||
},
|
||||
};
|
||||
if let Some(o) = info.as_object_mut() {
|
||||
o.insert("body".into(), json!(shape.name));
|
||||
}
|
||||
meshed.push((cell, info));
|
||||
}
|
||||
|
||||
// Replace the cells' meshes (replace.rs), each after the labels before it; other bodies
|
||||
// and the definitions stay.
|
||||
let model = &mut s.model;
|
||||
let cleared = super::replace::clear(model, names.iter().map(String::as_str));
|
||||
let mut report = Vec::with_capacity(meshed.len());
|
||||
for (cell, mut info) in meshed {
|
||||
let (kind, elements, nodes) = match &cell {
|
||||
Meshed::Hex(b, m) => {
|
||||
add_hex(model, b, m)?;
|
||||
(m.kind, m.element_count(), m.nodes.len())
|
||||
}
|
||||
Meshed::Tet(t) => {
|
||||
add_tets(model, &t.name, &t.face_names, &t.mesh)?;
|
||||
(t.mesh.kind, t.mesh.elements.len(), t.mesh.points.len())
|
||||
}
|
||||
};
|
||||
if let Some(o) = info.as_object_mut() {
|
||||
o.insert("kind".into(), json!(kind.name()));
|
||||
o.insert("elements".into(), json!(elements));
|
||||
o.insert("nodes".into(), json!(nodes));
|
||||
}
|
||||
report.push(info);
|
||||
}
|
||||
let interfaces = join(model, &names, COINCIDENT * diagonal)?;
|
||||
let (nodes, elements) = (model.nodes().len(), model.elements().len());
|
||||
Ok(cleared.report(s, json!({"cells": report, "interfaces": interfaces, "nodes": nodes, "elements": elements, "size": size})))
|
||||
}
|
||||
|
||||
/// One side of an interface: a cell's element faces on one side of a partition.
|
||||
struct Side {
|
||||
body: String,
|
||||
/// The face name (`partition:P:a`), which selects its pieces too.
|
||||
face: String,
|
||||
faces: Vec<ElementFace>,
|
||||
nodes: BTreeSet<u32>,
|
||||
lo: [f64; 3],
|
||||
hi: [f64; 3],
|
||||
}
|
||||
|
||||
/// The element faces of each cell tagged with a partition's cut faces, by partition and side.
|
||||
fn sides(model: &Model, cells: &[String]) -> BTreeMap<String, [Vec<Side>; 2]> {
|
||||
let c = model.classification();
|
||||
// Tag → (partition, side), for cut faces of the meshed cells.
|
||||
let mut cut: BTreeMap<u32, (String, usize, String)> = BTreeMap::new();
|
||||
for (t, r) in c.entities().iter().enumerate() {
|
||||
let Entity::Face(name) = &r.entity else { continue };
|
||||
if !cells.contains(&r.body) {
|
||||
continue;
|
||||
}
|
||||
let base = name.split_once('#').map_or(name.as_str(), |(b, _)| b);
|
||||
let Some(rest) = base.strip_prefix("partition:") else { continue };
|
||||
let Some((partition, side)) = rest.rsplit_once(':') else { continue };
|
||||
let side = match side {
|
||||
"a" => 0,
|
||||
"b" => 1,
|
||||
_ => continue,
|
||||
};
|
||||
if let Ok(t) = u32::try_from(t) {
|
||||
cut.insert(t, (partition.to_string(), side, r.body.clone()));
|
||||
}
|
||||
}
|
||||
let mut grouped: BTreeMap<(String, usize, String), Vec<ElementFace>> = BTreeMap::new();
|
||||
for (&element, tags) in c.elements() {
|
||||
for (&face, t) in &tags.faces {
|
||||
if let Some(key) = cut.get(t) {
|
||||
grouped.entry(key.clone()).or_default().push(ElementFace { element, face });
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out: BTreeMap<String, [Vec<Side>; 2]> = BTreeMap::new();
|
||||
for ((partition, side, body), faces) in grouped {
|
||||
let nodes: BTreeSet<u32> = faces.iter().filter_map(|f| model.face_nodes(*f)).flatten().collect();
|
||||
let (mut lo, mut hi) = ([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]);
|
||||
for n in nodes.iter().filter_map(|&n| model.node(n)) {
|
||||
for k in 0..3 {
|
||||
lo[k] = lo[k].min(n.xyz[k]);
|
||||
hi[k] = hi[k].max(n.xyz[k]);
|
||||
}
|
||||
}
|
||||
let face = format!("partition:{partition}:{}", if side == 0 { "a" } else { "b" });
|
||||
if let Some(slot) = out.entry(partition).or_insert_with(|| [Vec::new(), Vec::new()]).get_mut(side) {
|
||||
slot.push(Side { body, face, faces, nodes, lo, hi });
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Join the cells across every partition: merge where the two sides match node for node, tie
|
||||
/// where they do not. Returns the interfaces.
|
||||
fn join(model: &mut Model, cells: &[String], tol: f64) -> Result<Vec<Value>> {
|
||||
let mut out = Vec::new();
|
||||
for (partition, [a_sides, b_sides]) in sides(model, cells) {
|
||||
let mut k = 0;
|
||||
for a in &a_sides {
|
||||
for b in &b_sides {
|
||||
let overlap = (0..3).all(|i| a.lo[i] <= b.hi[i] + tol && b.lo[i] <= a.hi[i] + tol);
|
||||
if !overlap {
|
||||
continue;
|
||||
}
|
||||
k += 1;
|
||||
let matched = matching(model, a, b, tol);
|
||||
if let Some(map) = matched {
|
||||
let count = map.len();
|
||||
model.merge_nodes(&map)?;
|
||||
out.push(json!({"partition": partition, "cells": [a.body, b.body], "joined": "merged", "nodes": count}));
|
||||
} else {
|
||||
let name = format!("tie_{partition}_{k}");
|
||||
let (main, secondary) = if a.nodes.len() <= b.nodes.len() { (a, b) } else { (b, a) };
|
||||
let set = |side: &Side| -> Result<Set> { Ok(Set::of_geometry(vec![GeometryRef::face(side.body.as_str(), side.face.as_str())?])) };
|
||||
let (main_set, secondary_set) = (format!("{name}_main"), format!("{name}_secondary"));
|
||||
for (n, side) in [(&main_set, main), (&secondary_set, secondary)] {
|
||||
if model.set(n).is_some() {
|
||||
model.replace_set(n, set(side)?)?;
|
||||
} else {
|
||||
model.add_set(n, set(side)?)?;
|
||||
}
|
||||
}
|
||||
if model.tie(&name).is_some() {
|
||||
model.remove_tie(&name)?;
|
||||
}
|
||||
model.add_tie(&name, Tie::new(&main_set, &secondary_set))?;
|
||||
out.push(json!({
|
||||
"partition": partition,
|
||||
"cells": [a.body, b.body],
|
||||
"joined": "tied",
|
||||
"tie": name,
|
||||
"main": main.body,
|
||||
"secondary": secondary.body,
|
||||
"faces": [a.faces.len(), b.faces.len()],
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// When the two sides' nodes coincide one to one (within `tol`) and their faces are the same
|
||||
/// in number, the merge: each node of side `b` to the node of side `a` at its place (or the other
|
||||
/// way round, so the lower label survives).
|
||||
fn matching(model: &Model, a: &Side, b: &Side, tol: f64) -> Option<BTreeMap<u32, u32>> {
|
||||
if a.nodes.len() != b.nodes.len() || a.faces.len() != b.faces.len() {
|
||||
return None;
|
||||
}
|
||||
let both: BTreeSet<u32> = a.nodes.union(&b.nodes).copied().collect();
|
||||
let map = fieldcraft_mesh::join::coincident_nodes(model, Some(&both), tol).ok()?;
|
||||
// Every pair joins one node of each side, and every node of either side is in a pair.
|
||||
let one_to_one = map.len() == a.nodes.len()
|
||||
&& map.iter().all(|(from, to)| (a.nodes.contains(from) && b.nodes.contains(to)) || (b.nodes.contains(from) && a.nodes.contains(to)));
|
||||
one_to_one.then_some(map)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The sample plate (40 × 30 × 10, a Ø10 hole at (15, 15)) open and cut at x = 30, right of
|
||||
/// the hole: `Body1/a` holds the hole, `Body1/b` is a 10 × 30 × 10 block.
|
||||
fn cut_plate() -> (crate::tests::TempDir, Session) {
|
||||
let (dir, path) = crate::tests::sample_design_file(&fieldcraft_geometry::sample::Plate::default());
|
||||
let mut s = Session::default();
|
||||
s.execute("geometry.open", &json!({"path": path})).unwrap();
|
||||
s.execute("geometry.datum", &json!({"name": "X30", "by": {"type": "offset", "plane": "yz", "offset": 30}})).unwrap();
|
||||
s.execute("geometry.partition", &json!({"name": "P", "datum": "X30"})).unwrap();
|
||||
(dir, s)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_and_tet_cells_are_tied_and_matching_hex_cells_merged() {
|
||||
let (_dir, mut s) = cut_plate();
|
||||
// A tet cell next to a hex cell: tied, main the coarser side.
|
||||
let r = s.execute("mesh.cells", &json!({"methods": {"Body1/a": "tet", "Body1/b": "mapped"}, "size": 2.5})).unwrap();
|
||||
assert_eq!(r["cells"][0]["kind"], "tet4", "{r}");
|
||||
assert_eq!(r["cells"][1]["kind"], "hex8", "{r}");
|
||||
let i = &r["interfaces"][0];
|
||||
assert_eq!(i["joined"], "tied", "{r}");
|
||||
assert_eq!(s.model.ties().len(), 1);
|
||||
for set in ["tie_P_1_main", "tie_P_1_secondary"] {
|
||||
assert!(s.model.resolve_set(set).unwrap().faces.len() > 4, "{set}");
|
||||
}
|
||||
// Both cells hex at one size: the plane faces match node for node and merge.
|
||||
let r = s.execute("mesh.cells", &json!({"default": "hex", "size": 2.5})).unwrap();
|
||||
assert_eq!(r["interfaces"].as_array().map(Vec::len), Some(1), "{r}");
|
||||
let i = &r["interfaces"][0];
|
||||
assert_eq!(i["joined"], "merged", "{r}");
|
||||
let separate = r["cells"].as_array().unwrap().iter().map(|c| c["nodes"].as_u64().unwrap()).sum::<u64>();
|
||||
assert_eq!(r["nodes"].as_u64().unwrap() + i["nodes"].as_u64().unwrap(), separate, "{r}");
|
||||
// Rerunning replaces the tie it made rather than adding another.
|
||||
s.execute("mesh.cells", &json!({"methods": {"Body1/a": "tet"}, "size": 2.5})).unwrap();
|
||||
assert_eq!(s.model.ties().len(), 1);
|
||||
}
|
||||
|
||||
/// The half crank arm (cut on its symmetry plane only) has no cell that maps or sweeps as
|
||||
/// the design gives it; the extrusion decomposes its cross-section into blocks itself, alike
|
||||
/// through mesh.hex.generate (auto) and mesh.cells, with no seeds.
|
||||
#[test]
|
||||
fn the_half_crank_extrudes_in_blocks_without_partitions() {
|
||||
let bytes = fieldcraft_geometry::script_design(crate::sample::CRANK_ARM).unwrap();
|
||||
let (_dir, path) = crate::tests::design_file(&bytes);
|
||||
let mut s = Session::default();
|
||||
s.execute("geometry.open", &json!({"path": path})).unwrap();
|
||||
s.execute("geometry.datum", &json!({"name": "Sym", "by": {"type": "offset", "plane": "zx", "offset": 0}})).unwrap();
|
||||
s.execute("geometry.partition", &json!({"name": "Half", "datum": "Sym"})).unwrap();
|
||||
let r = s.execute("mesh.hex.generate", &json!({"body": "CrankArm/a", "size": 3})).unwrap();
|
||||
let body = &r["bodies"][0];
|
||||
assert_eq!(body["method"], "extrude", "{r}");
|
||||
assert!(body["description"].as_str().unwrap().contains(" 0 free)"), "{r}");
|
||||
assert!(body["quality"]["min_scaled_jacobian"].as_f64().unwrap() >= 0.37, "{r}");
|
||||
let r = s.execute("mesh.cells", &json!({"bodies": ["CrankArm/a"], "default": "extrude", "size": 3})).unwrap();
|
||||
assert_eq!(r["cells"][0]["method"], "extrude", "{r}");
|
||||
assert_eq!(r["elements"], body["elements"], "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_falls_back_to_tet_and_says_why() {
|
||||
let (_dir, mut s) = cut_plate();
|
||||
let r = s.execute("mesh.cells", &json!({"default": "mapped", "methods": {"Body1/a": "auto"}, "size": 3})).unwrap();
|
||||
// The holed cell is not a mapped block, but auto sweeps it.
|
||||
assert!(r["cells"][0]["method"].as_str().is_some(), "{r}");
|
||||
assert_eq!(r["cells"][1]["method"], "mapped", "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_params_change_nothing() {
|
||||
let (_dir, mut s) = cut_plate();
|
||||
let journal = s.journal.len();
|
||||
for p in [
|
||||
json!({"default": "pyramid"}),
|
||||
json!({"methods": {"Nope": "tet"}}),
|
||||
json!({"methods": ["tet"]}),
|
||||
json!({"bodies": []}),
|
||||
json!({"bodies": ["Body1/a", "Body1/a"]}),
|
||||
json!({"bodies": ["Nope"]}),
|
||||
json!({"order": 3}),
|
||||
json!({"size": -1}),
|
||||
json!({"default": "mapped", "bodies": ["Body1/a"]}),
|
||||
] {
|
||||
assert!(s.execute("mesh.cells", &p).is_err(), "{p}");
|
||||
}
|
||||
assert_eq!(s.journal.len(), journal);
|
||||
assert!(s.model.elements().is_empty());
|
||||
}
|
||||
|
||||
/// A 40 × 10 × 10 bar in uniaxial tension, cut in the middle: one half hex, the other tet,
|
||||
/// tied. With ν = 0, symmetry conditions on three faces and the end load spread by consistent
|
||||
/// weights, the stress is uniform, which both elements and the dual mortar tie carry exactly:
|
||||
/// the end moves F L / (E A).
|
||||
#[test]
|
||||
fn a_tied_hex_tet_bar_in_tension_stretches_as_the_formula_says() {
|
||||
let commands = json!({"commands": [
|
||||
{"command": "solid.box", "params": {"length": 40, "width": 10, "height": 10, "body_name": "Bar"}},
|
||||
]});
|
||||
let bytes = fieldcraft_geometry::script_design(&commands.to_string()).unwrap();
|
||||
let (_dir, path) = crate::tests::design_file(&bytes);
|
||||
let mut s = Session::default();
|
||||
s.execute("geometry.open", &json!({"path": path})).unwrap();
|
||||
let bbox = s.execute("geometry.bodies", &json!({})).unwrap()[0]["bbox"].clone();
|
||||
let lo: Vec<f64> = bbox[0].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
|
||||
let hi: Vec<f64> = bbox[1].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
|
||||
let (axis, length) = (0..3).map(|k| (k, hi[k] - lo[k])).max_by(|a, b| a.1.total_cmp(&b.1)).unwrap();
|
||||
assert!((length - 40.0).abs() < 1e-9);
|
||||
let mid = (lo[axis] + hi[axis]) / 2.0;
|
||||
let mut normal = [0.0; 3];
|
||||
normal[axis] = 1.0;
|
||||
let mut point = [0.0; 3];
|
||||
point[axis] = mid;
|
||||
s.execute("geometry.datum", &json!({"name": "Mid", "by": {"type": "point_normal", "point": point, "normal": normal}})).unwrap();
|
||||
s.execute("geometry.partition", &json!({"name": "Cut", "datum": "Mid"})).unwrap();
|
||||
let r = s.execute("mesh.cells", &json!({"methods": {"Bar/a": "mapped", "Bar/b": "tet"}, "size": 2.5})).unwrap();
|
||||
assert_eq!(r["interfaces"][0]["joined"], "tied", "{r}");
|
||||
|
||||
let m = &s.model;
|
||||
let on = |k: usize, v: f64| -> Vec<u32> { m.nodes().iter().filter(|(_, n)| (n.xyz[k] - v).abs() < 1e-9).map(|(l, _)| *l).collect() };
|
||||
let others: Vec<usize> = (0..3).filter(|k| *k != axis).collect();
|
||||
let end: Vec<Value> = m
|
||||
.elements()
|
||||
.iter()
|
||||
.flat_map(|(&e, el)| (1..=el.kind.faces().len() as u8).map(move |f| (e, f)))
|
||||
.filter(|&(e, f)| {
|
||||
m.face_nodes(ElementFace { element: e, face: f })
|
||||
.is_some_and(|ns| ns.iter().all(|n| (m.node(*n).unwrap().xyz[axis] - hi[axis]).abs() < 1e-9))
|
||||
})
|
||||
.map(|(e, f)| json!({"element": e, "face": f}))
|
||||
.collect();
|
||||
let plane = |k: usize| ["x", "y", "z"][k];
|
||||
let (young, area, force) = (70_000.0, 100.0, 1000.0);
|
||||
let script = json!([
|
||||
{"command": "model.set.create", "params": {"name": "all", "elements": m.elements().keys().collect::<Vec<_>>()}},
|
||||
{"command": "model.set.create", "params": {"name": "root", "nodes": on(axis, lo[axis])}},
|
||||
{"command": "model.set.create", "params": {"name": "side1", "nodes": on(others[0], lo[others[0]])}},
|
||||
{"command": "model.set.create", "params": {"name": "side2", "nodes": on(others[1], lo[others[1]])}},
|
||||
{"command": "model.set.create", "params": {"name": "end", "faces": end}},
|
||||
{"command": "model.material.create", "params": {"name": "Al", "elastic": {"type": "isotropic", "young": young, "poisson": 0}}},
|
||||
{"command": "model.section.create", "params": {"name": "Bar", "set": "all", "material": "Al", "kind": {"type": "solid"}}},
|
||||
{"command": "model.boundary_condition.create", "params": {"name": "s0", "type": "symmetry", "target": {"set": "root"}, "plane": plane(axis)}},
|
||||
{"command": "model.boundary_condition.create", "params": {"name": "s1", "type": "symmetry", "target": {"set": "side1"}, "plane": plane(others[0])}},
|
||||
{"command": "model.boundary_condition.create", "params": {"name": "s2", "type": "symmetry", "target": {"set": "side2"}, "plane": plane(others[1])}},
|
||||
{"command": "model.load.create", "params": {"name": "Pull", "type": "force", "target": {"set": "end"}, "vector": normal.map(|n| n * force)}},
|
||||
{"command": "model.step.create", "params": {"name": "Load", "procedure": {"type": "static"}, "boundary_conditions": ["s0", "s1", "s2"], "loads": ["Pull"]}},
|
||||
]);
|
||||
let tip = on(axis, hi[axis]);
|
||||
s.run_script(&script).unwrap();
|
||||
s.execute("solve.static", &json!({})).unwrap();
|
||||
let probe = s.execute("solve.probe", &json!({"step": "Load", "nodes": tip})).unwrap();
|
||||
let expected = force * length / (young * area);
|
||||
let probed = probe["nodes"].as_array().unwrap();
|
||||
assert!(probed.len() > 4, "{probe}");
|
||||
for n in probed {
|
||||
let u = n["displacement"][axis].as_f64().unwrap();
|
||||
assert!((u - expected).abs() < 1e-6 * expected, "{u} vs {expected}: {n}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@
|
||||
//! touch there. Each touching pair is reported with the faces of each side that are close to the
|
||||
//! other; with `create`, each becomes two face sets and a contact pair.
|
||||
|
||||
use crate::schema::ProblemKind;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use fieldcraft_fem::contact::{Grid, bounds, closest_point};
|
||||
@@ -19,6 +20,7 @@ use fieldcraft_model::{Contact, ContactSurfaces, ElementFace, Friction, InitialP
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{name, opt};
|
||||
use crate::requirement::Requirement;
|
||||
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
|
||||
|
||||
/// The options every contact takes, from the parameters.
|
||||
@@ -33,7 +35,7 @@ fn contact(p: &Value, surfaces: ContactSurfaces) -> Result<Contact> {
|
||||
|
||||
/// A required name-valued parameter.
|
||||
fn text<'a>(p: &'a Value, key: &str) -> Result<&'a str> {
|
||||
p.get(key).and_then(Value::as_str).ok_or_else(|| EngineError::Params(format!("`{key}` must be a set name")))
|
||||
p.get(key).and_then(Value::as_str).ok_or_else(|| EngineError::param(key, ProblemKind::NotAName))
|
||||
}
|
||||
|
||||
pub const PAIR: CommandSpec = CommandSpec {
|
||||
@@ -46,6 +48,7 @@ pub const PAIR: CommandSpec = CommandSpec {
|
||||
),
|
||||
form: Some(super::forms::CONTACT_PAIR),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Set],
|
||||
run: |s: &mut Session, p: &Value| {
|
||||
let n = name(p)?;
|
||||
let surfaces = ContactSurfaces::Pair { main: text(p, "main")?.to_string(), secondary: text(p, "secondary")?.to_string() };
|
||||
@@ -64,6 +67,7 @@ pub const GENERAL: CommandSpec = CommandSpec {
|
||||
),
|
||||
form: Some(super::forms::CONTACT_GENERAL),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[],
|
||||
run: |s: &mut Session, p: &Value| {
|
||||
let n = name(p)?;
|
||||
let surface = match p.get("surface") {
|
||||
@@ -81,6 +85,7 @@ pub const EDIT: CommandSpec = CommandSpec {
|
||||
params: r#"{"name": "impact", "surfaces": {"type": "pair", "main": "plate", "secondary": "ball"} | {"type": "general", "surface": "skin" (optional)}, "friction": {…}, "penalty_scale": 1, "initial_penetration": "adjust|refuse"} — replaces the contact of that name (the model's form; see interaction.contact.pair)"#,
|
||||
form: Some(super::forms::CONTACT_EDIT),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Contact],
|
||||
run: |s: &mut Session, p: &Value| {
|
||||
let n = name(p)?;
|
||||
let mut obj = p.as_object().cloned().ok_or_else(|| EngineError::Params("the parameters of a contact are a JSON object".into()))?;
|
||||
@@ -97,6 +102,7 @@ pub const DELETE: CommandSpec = CommandSpec {
|
||||
params: r#"{"name": "impact"}"#,
|
||||
form: Some(super::forms::CONTACT_DELETE),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Contact],
|
||||
run: |s: &mut Session, p: &Value| {
|
||||
s.model.remove_contact(name(p)?)?;
|
||||
Ok(Value::Null)
|
||||
@@ -118,6 +124,7 @@ pub const TIE: CommandSpec = CommandSpec {
|
||||
params: r#"{"name": "glue", "main": "plate" (a set of element faces), "secondary": "rib" (another), "position_tolerance": 0.1 (optional: how far a secondary node may lie from the main surface and still be tied; default half the main element's thickness)} — bonds the secondary surface to the main one across non-matching meshes: each secondary node follows the main surface under it (dual mortar constraints in the implicit analyses; a constant stress crosses the tie exactly); fails if the name is taken"#,
|
||||
form: Some(super::forms::TIE),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Set],
|
||||
run: |s: &mut Session, p: &Value| {
|
||||
let n = name(p)?;
|
||||
s.model.add_tie(n, tie(p)?)?;
|
||||
@@ -131,6 +138,7 @@ pub const TIE_EDIT: CommandSpec = CommandSpec {
|
||||
params: r#"{"name": "glue", "main": "plate", "secondary": "rib", "position_tolerance": 0.1} — replaces the tie of that name (see interaction.tie)"#,
|
||||
form: Some(super::forms::TIE_EDIT),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Tie],
|
||||
run: |s: &mut Session, p: &Value| {
|
||||
let n = name(p)?;
|
||||
s.model.replace_tie(n, tie(p)?)?;
|
||||
@@ -144,6 +152,7 @@ pub const TIE_DELETE: CommandSpec = CommandSpec {
|
||||
params: r#"{"name": "glue"}"#,
|
||||
form: Some(super::forms::TIE_DELETE),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Tie],
|
||||
run: |s: &mut Session, p: &Value| {
|
||||
s.model.remove_tie(name(p)?)?;
|
||||
Ok(Value::Null)
|
||||
@@ -159,6 +168,7 @@ pub const FIND: CommandSpec = CommandSpec {
|
||||
),
|
||||
form: Some(super::forms::CONTACT_FIND),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Mesh],
|
||||
run: find,
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,730 @@
|
||||
//! Datum planes, axes and points, and partitions of the open design by datum planes.
|
||||
//!
|
||||
//! Datums and partitions are part of the model (`fieldcraft_model::datums`). A datum point is
|
||||
//! placed by coordinates, at a mesh vertex, along a design edge, at a design face's centre or
|
||||
//! where a datum axis crosses a datum plane; planes and axes can be made through datum points.
|
||||
//! Each takes the coordinates of what it is made from when it is made (a later edit of a datum
|
||||
//! point leaves the planes and axes made through it where they are). A partition cuts the
|
||||
//! design in memory (`fieldcraft_geometry::partition`); the model's partitions are applied again,
|
||||
//! in order, whenever the design is opened (`geometry.open`, `file.open`, samples), so an edit
|
||||
//! of the design followed by a re-open replays them.
|
||||
|
||||
use crate::schema::ProblemKind;
|
||||
use std::sync::Arc;
|
||||
|
||||
use fieldcraft_geometry::{Cut, Design};
|
||||
use fieldcraft_io::{Item, ItemKind, MAX_HIDDEN};
|
||||
use fieldcraft_model::{Datum, Model, Partition};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::requirement::Requirement;
|
||||
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
|
||||
|
||||
pub const DATUM_PLANE: CommandSpec = CommandSpec {
|
||||
id: "geometry.datum",
|
||||
label: "Datum Plane",
|
||||
params: r#"{"name": "Mid", "by": {"type": "offset", "plane": "yz" | "zx" | "xy", "offset": 15} | {"type": "three_points", "a": [x, y, z], "b": […], "c": […]} | {"type": "point_normal", "point": [x, y, z], "normal": [nx, ny, nz]} | {"type": "datum_points", "a": "P1", "b": "P2", "c": "P3"} | {"type": "normal_to_axis", "axis": "Spindle", "point"?: "P1"}} — a named datum plane (model coordinates, mm for SolidCraft geometry): a principal plane moved along its normal (yz: normal +x, zx: normal +y, xy: normal +z), through three points or three datum points (normal (b − a) × (c − a)), through a point with a normal, or normal to a datum axis through a datum point (the axis's point by default). Partitions (geometry.partition) cut by it; shown in the viewport"#,
|
||||
form: Some(super::forms::DATUM_PLANE),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[],
|
||||
run: datum_plane,
|
||||
};
|
||||
|
||||
pub const DATUM_AXIS: CommandSpec = CommandSpec {
|
||||
id: "geometry.datum.axis",
|
||||
label: "Datum Axis",
|
||||
params: r#"{"name": "Spindle", "by": {"type": "principal", "axis": "x" | "y" | "z", "through"?: [x, y, z] (default the origin)} | {"type": "two_points", "a": [x, y, z], "b": […]} | {"type": "point_direction", "point": [x, y, z], "direction": [dx, dy, dz]} | {"type": "datum_points", "a": "P1", "b": "P2"}} — a named datum axis, shown in the viewport"#,
|
||||
form: Some(super::forms::DATUM_AXIS),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[],
|
||||
run: datum_axis,
|
||||
};
|
||||
|
||||
pub const DATUM_POINT: CommandSpec = CommandSpec {
|
||||
id: "geometry.datum.point",
|
||||
label: "Datum Point",
|
||||
params: r#"{"name": "P1", "by": {"type": "coordinates", "point": [x, y, z]} | {"type": "vertex", "body": "Body1", "vertex": "v3"} | {"type": "edge", "body": "Body1", "edge": "F1:top|F2:side", "fraction"?: 0.5} | {"type": "face_centre", "body": "Body1", "face": "F2:top"} | {"type": "axis_plane", "axis": "Spindle", "plane": "Mid"}} — a named datum point, shown in the viewport as a small cross: at coordinates, at a vertex of the mesh (as its geometry tags name it), a fraction along an edge of the open design (0.5: its midpoint), at the area centre of a face of the open design, or where a datum axis crosses a datum plane. Datum planes and axes can be made through datum points"#,
|
||||
form: Some(super::forms::DATUM_POINT),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[],
|
||||
run: datum_point,
|
||||
};
|
||||
|
||||
pub const DATUM_EDIT: CommandSpec = CommandSpec {
|
||||
id: "geometry.datum.edit",
|
||||
label: "Edit Datum Plane",
|
||||
params: r#"{"name": "Mid", "by": …} — redefines a datum plane (the parameters of geometry.datum); the partitions that cut by it cut again"#,
|
||||
form: Some(super::forms::DATUM_PLANE),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::DatumPlane],
|
||||
run: |s, p| datum_edit(s, p, "plane"),
|
||||
};
|
||||
|
||||
pub const DATUM_AXIS_EDIT: CommandSpec = CommandSpec {
|
||||
id: "geometry.datum.axis.edit",
|
||||
label: "Edit Datum Axis",
|
||||
params: r#"{"name": "Spindle", "by": …} — redefines a datum axis (the parameters of geometry.datum.axis)"#,
|
||||
form: Some(super::forms::DATUM_AXIS),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::DatumAxis],
|
||||
run: |s, p| datum_edit(s, p, "axis"),
|
||||
};
|
||||
|
||||
pub const DATUM_POINT_EDIT: CommandSpec = CommandSpec {
|
||||
id: "geometry.datum.point.edit",
|
||||
label: "Edit Datum Point",
|
||||
params: r#"{"name": "P1", "by": …} — redefines a datum point (the parameters of geometry.datum.point); planes and axes made through it stay where they are"#,
|
||||
form: Some(super::forms::DATUM_POINT),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::DatumPoint],
|
||||
run: |s, p| datum_edit(s, p, "point"),
|
||||
};
|
||||
|
||||
pub const DATUM_DELETE: CommandSpec = CommandSpec {
|
||||
id: "geometry.datum.delete",
|
||||
label: "Delete Datum",
|
||||
params: r#"{"name": "Mid", "cascade"?: false} — deletes a datum plane, axis or point; one a partition cuts by is refused (naming the partitions), unless `cascade` deletes those partitions too"#,
|
||||
form: Some(super::forms::DATUM_DELETE),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Datum],
|
||||
run: datum_delete,
|
||||
};
|
||||
|
||||
pub const PARTITION: CommandSpec = CommandSpec {
|
||||
id: "geometry.partition",
|
||||
label: "Partition",
|
||||
params: r#"{"name": "Half", "datum": "Mid", "bodies"?: ["Body1"] (default: every body the plane divides)} — cuts bodies of the open design into cells by a datum plane, in memory (the design file is not changed); the model keeps the partition and applies it again whenever the design is opened, after the partitions before it. A cut body `B` becomes the cells `B/a` (on the plane's negative side) and `B/b` (several pieces on a side: `B/a1`, `B/a2`, …). The two faces of the cut are paired by name: `partition:<name>:a` on the cells on the negative side, `partition:<name>:b` on the positive side (`…#0`, `…#1` where a cell has several); every other face keeps the persistent name of the face it is a piece of (`<face>#k` for several pieces on one cell), so sets by face name still select it. Reports the cells made and the cut faces named; a plane that divides no body, or a listed body it does not divide, is an error"#,
|
||||
form: Some(super::forms::PARTITION),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Design, Requirement::DatumPlane],
|
||||
run: partition,
|
||||
};
|
||||
|
||||
pub const PARTITION_DELETE: CommandSpec = CommandSpec {
|
||||
id: "geometry.partition.delete",
|
||||
label: "Delete Partition",
|
||||
params: r#"{"name": "Half"} — removes a partition; the design is cut again by the ones left"#,
|
||||
form: Some(super::forms::PARTITION_DELETE),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Partition],
|
||||
run: partition_delete,
|
||||
};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
enum Principal {
|
||||
Yz,
|
||||
Zx,
|
||||
Xy,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
|
||||
enum PlaneBy {
|
||||
Offset {
|
||||
plane: Principal,
|
||||
#[serde(default)]
|
||||
offset: f64,
|
||||
},
|
||||
ThreePoints {
|
||||
a: [f64; 3],
|
||||
b: [f64; 3],
|
||||
c: [f64; 3],
|
||||
},
|
||||
PointNormal {
|
||||
point: [f64; 3],
|
||||
normal: [f64; 3],
|
||||
},
|
||||
DatumPoints {
|
||||
a: String,
|
||||
b: String,
|
||||
c: String,
|
||||
},
|
||||
NormalToAxis {
|
||||
axis: String,
|
||||
#[serde(default)]
|
||||
point: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
enum Axis {
|
||||
X,
|
||||
Y,
|
||||
Z,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
|
||||
enum AxisBy {
|
||||
Principal {
|
||||
axis: Axis,
|
||||
#[serde(default)]
|
||||
through: [f64; 3],
|
||||
},
|
||||
TwoPoints {
|
||||
a: [f64; 3],
|
||||
b: [f64; 3],
|
||||
},
|
||||
PointDirection {
|
||||
point: [f64; 3],
|
||||
direction: [f64; 3],
|
||||
},
|
||||
DatumPoints {
|
||||
a: String,
|
||||
b: String,
|
||||
},
|
||||
}
|
||||
|
||||
fn half() -> f64 {
|
||||
0.5
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
|
||||
enum PointBy {
|
||||
Coordinates {
|
||||
point: [f64; 3],
|
||||
},
|
||||
Vertex {
|
||||
body: String,
|
||||
vertex: String,
|
||||
},
|
||||
Edge {
|
||||
body: String,
|
||||
edge: String,
|
||||
#[serde(default = "half")]
|
||||
fraction: f64,
|
||||
},
|
||||
FaceCentre {
|
||||
body: String,
|
||||
face: String,
|
||||
},
|
||||
AxisPlane {
|
||||
axis: String,
|
||||
plane: String,
|
||||
},
|
||||
}
|
||||
|
||||
fn sub(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
|
||||
[a[0] - b[0], a[1] - b[1], a[2] - b[2]]
|
||||
}
|
||||
|
||||
/// The coordinates of datum point `name`.
|
||||
fn datum_point_at(m: &Model, name: &str) -> Result<[f64; 3]> {
|
||||
match m.datum(name) {
|
||||
Some(d) => d.point().ok_or_else(|| EngineError::Params(format!("datum `{name}` is a datum {}, not a point", d.kind()))),
|
||||
None => Err(EngineError::Params(format!("no datum point `{name}`"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The point and unit direction of datum axis `name`.
|
||||
fn datum_axis_of(m: &Model, name: &str) -> Result<([f64; 3], [f64; 3])> {
|
||||
match m.datum(name) {
|
||||
Some(d) => d.axis().ok_or_else(|| EngineError::Params(format!("datum `{name}` is a datum {}, not an axis", d.kind()))),
|
||||
None => Err(EngineError::Params(format!("no datum axis `{name}`"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// A plane through three points; collinear points are refused relative to their spread.
|
||||
fn three_points(a: [f64; 3], b: [f64; 3], c: [f64; 3]) -> Result<Datum> {
|
||||
let (u, v) = (sub(b, a), sub(c, a));
|
||||
let n = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]];
|
||||
let size = u.iter().chain(&v).map(|x| x * x).sum::<f64>();
|
||||
if !(n.iter().map(|x| x * x).sum::<f64>() > 1e-20 * size * size) {
|
||||
return Err(EngineError::Params("the three points must not lie on one line".into()));
|
||||
}
|
||||
Ok(Datum::Plane { point: a, normal: n })
|
||||
}
|
||||
|
||||
fn plane_datum(m: &Model, by: PlaneBy) -> Result<Datum> {
|
||||
Ok(match by {
|
||||
PlaneBy::Offset { plane, offset } => {
|
||||
if !offset.is_finite() {
|
||||
return Err(EngineError::param("offset", ProblemKind::NotANumber));
|
||||
}
|
||||
let normal = match plane {
|
||||
Principal::Yz => [1.0, 0.0, 0.0],
|
||||
Principal::Zx => [0.0, 1.0, 0.0],
|
||||
Principal::Xy => [0.0, 0.0, 1.0],
|
||||
};
|
||||
Datum::Plane { point: normal.map(|n| n * offset), normal }
|
||||
}
|
||||
PlaneBy::ThreePoints { a, b, c } => three_points(a, b, c)?,
|
||||
PlaneBy::PointNormal { point, normal } => Datum::Plane { point, normal },
|
||||
PlaneBy::DatumPoints { a, b, c } => three_points(datum_point_at(m, &a)?, datum_point_at(m, &b)?, datum_point_at(m, &c)?)?,
|
||||
PlaneBy::NormalToAxis { axis, point } => {
|
||||
let (on_axis, direction) = datum_axis_of(m, &axis)?;
|
||||
let point = match point {
|
||||
Some(p) => datum_point_at(m, &p)?,
|
||||
None => on_axis,
|
||||
};
|
||||
Datum::Plane { point, normal: direction }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn axis_datum(m: &Model, by: AxisBy) -> Result<Datum> {
|
||||
Ok(match by {
|
||||
AxisBy::Principal { axis, through } => {
|
||||
let direction = match axis {
|
||||
Axis::X => [1.0, 0.0, 0.0],
|
||||
Axis::Y => [0.0, 1.0, 0.0],
|
||||
Axis::Z => [0.0, 0.0, 1.0],
|
||||
};
|
||||
Datum::Axis { point: through, direction }
|
||||
}
|
||||
AxisBy::TwoPoints { a, b } => Datum::Axis { point: a, direction: sub(b, a) },
|
||||
AxisBy::PointDirection { point, direction } => Datum::Axis { point, direction },
|
||||
AxisBy::DatumPoints { a, b } => {
|
||||
let a = datum_point_at(m, &a)?;
|
||||
Datum::Axis { point: a, direction: sub(datum_point_at(m, &b)?, a) }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Most mesh nodes a vertex is looked for among.
|
||||
const MAX_VERTEX_NODES: usize = 10_000_000;
|
||||
|
||||
fn point_datum(s: &Session, by: PointBy) -> Result<Datum> {
|
||||
let shape = |body: &str| -> Result<&fieldcraft_geometry::Shape> {
|
||||
let design = s.design.as_deref().ok_or_else(|| EngineError::Params("open a design first".into()))?;
|
||||
design.body(body).ok_or_else(|| EngineError::Params(format!("the design has no body `{body}`")))
|
||||
};
|
||||
let point = match by {
|
||||
PointBy::Coordinates { point } => point,
|
||||
PointBy::Vertex { body, vertex } => {
|
||||
let m = &s.model;
|
||||
let at = fieldcraft_model::GeometryRef::new(body.clone(), fieldcraft_model::Entity::Vertex(vertex.clone()))?;
|
||||
let tags = m.classification().tags_selected_by(&at);
|
||||
let node =
|
||||
m.classification().nodes().iter().take(MAX_VERTEX_NODES).find(|(_, t)| tags.contains(t)).and_then(|(n, _)| m.node(*n)).ok_or_else(
|
||||
|| EngineError::Params(format!("vertex `{vertex}` of body `{body}` is on no mesh node (vertices are named on meshed bodies)")),
|
||||
)?;
|
||||
node.xyz
|
||||
}
|
||||
PointBy::Edge { body, edge, fraction } => {
|
||||
if !(0.0..=1.0).contains(&fraction) {
|
||||
return Err(EngineError::invalid("fraction", "is a number from 0 to 1".to_string()));
|
||||
}
|
||||
let edges = shape(&body)?.edges()?;
|
||||
let e = edges.iter().find(|e| e.name == edge).ok_or_else(|| EngineError::Params(format!("body `{body}` has no edge `{edge}`")))?;
|
||||
e.point_at(fraction).ok_or_else(|| EngineError::Params(format!("edge `{edge}` of body `{body}` has no points")))?
|
||||
}
|
||||
PointBy::FaceCentre { body, face } => shape(&body)?.face_centre(&face)?,
|
||||
PointBy::AxisPlane { axis, plane } => {
|
||||
let (p, d) = datum_axis_of(&s.model, &axis)?;
|
||||
let (q, n) = match s.model.datum(&plane) {
|
||||
Some(x) => x.plane().ok_or_else(|| EngineError::Params(format!("datum `{plane}` is a datum {}, not a plane", x.kind())))?,
|
||||
None => return Err(EngineError::Params(format!("no datum plane `{plane}`"))),
|
||||
};
|
||||
let along = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
|
||||
let across = along(d, n);
|
||||
// Unit vectors: the sine of the angle between the axis and the plane.
|
||||
if across.abs() < 1e-9 {
|
||||
return Err(EngineError::Params(format!("axis `{axis}` is parallel to plane `{plane}`: they do not cross")));
|
||||
}
|
||||
let t = along(sub(q, p), n) / across;
|
||||
[p[0] + t * d[0], p[1] + t * d[1], p[2] + t * d[2]]
|
||||
}
|
||||
};
|
||||
Ok(Datum::Point { point })
|
||||
}
|
||||
|
||||
/// The datum `by` defines for a datum of `kind` (`plane`, `axis` or `point`).
|
||||
fn datum_of(s: &Session, kind: &str, p: &Value) -> Result<Datum> {
|
||||
match kind {
|
||||
"plane" => plane_datum(&s.model, super::req(p, "by")?),
|
||||
"axis" => axis_datum(&s.model, super::req(p, "by")?),
|
||||
_ => point_datum(s, super::req(p, "by")?),
|
||||
}
|
||||
}
|
||||
|
||||
/// The parameters of the command that edits datum `name`, describing it as it is (a plane by
|
||||
/// its point and normal, an axis by its point and direction, a point by its coordinates); and
|
||||
/// that command.
|
||||
pub fn edit_params(name: &str, d: &Datum) -> (&'static str, Value) {
|
||||
match *d {
|
||||
Datum::Plane { point, normal } => (DATUM_EDIT.id, json!({"name": name, "by": {"type": "point_normal", "point": point, "normal": normal}})),
|
||||
Datum::Axis { point, direction } => {
|
||||
(DATUM_AXIS_EDIT.id, json!({"name": name, "by": {"type": "point_direction", "point": point, "direction": direction}}))
|
||||
}
|
||||
Datum::Point { point } => (DATUM_POINT_EDIT.id, json!({"name": name, "by": {"type": "coordinates", "point": point}})),
|
||||
}
|
||||
}
|
||||
|
||||
fn datum_json(name: &str, d: &Datum) -> Value {
|
||||
let mut v = serde_json::to_value(d).unwrap_or(Value::Null);
|
||||
if let Some(o) = v.as_object_mut() {
|
||||
o.insert("name".into(), json!(name));
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
fn datum_create(s: &mut Session, p: &Value, kind: &str) -> Result<Value> {
|
||||
let name = super::name(p)?;
|
||||
let datum = datum_of(s, kind, p)?;
|
||||
s.model.add_datum(name, datum)?;
|
||||
Ok(datum_json(name, s.model.datum(name).unwrap_or(&datum)))
|
||||
}
|
||||
|
||||
fn datum_plane(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
datum_create(s, p, "plane")
|
||||
}
|
||||
|
||||
fn datum_axis(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
datum_create(s, p, "axis")
|
||||
}
|
||||
|
||||
fn datum_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
datum_create(s, p, "point")
|
||||
}
|
||||
|
||||
/// Redefine datum `name` of `kind`; the partitions that cut by a plane cut again.
|
||||
fn datum_edit(s: &mut Session, p: &Value, kind: &str) -> Result<Value> {
|
||||
let name = super::name(p)?;
|
||||
match s.model.datum(name) {
|
||||
Some(d) if d.kind() == kind => {}
|
||||
Some(d) => return Err(EngineError::Params(format!("datum `{name}` is a datum {}, not a {kind}", d.kind()))),
|
||||
None => return Err(EngineError::Params(format!("no datum {kind} `{name}`"))),
|
||||
}
|
||||
let datum = datum_of(s, kind, p)?;
|
||||
s.model.replace_datum(name, datum)?;
|
||||
if !s.model.datum_users(name).is_empty() {
|
||||
recut(s)?;
|
||||
}
|
||||
Ok(datum_json(name, s.model.datum(name).unwrap_or(&datum)))
|
||||
}
|
||||
|
||||
fn datum_delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = super::name(p)?;
|
||||
let cascade: bool = super::opt(p, "cascade")?.unwrap_or(false);
|
||||
let partitions: Vec<String> = s.model.partitions().iter().filter(|x| x.datum == name).map(|x| x.name.clone()).collect();
|
||||
if cascade {
|
||||
for partition in &partitions {
|
||||
s.model.remove_partition(partition)?;
|
||||
}
|
||||
}
|
||||
s.model.remove_datum(name)?;
|
||||
if cascade && !partitions.is_empty() {
|
||||
recut(s)?;
|
||||
}
|
||||
Ok(json!({"deleted": name, "partitions": if cascade { partitions } else { Vec::new() }}))
|
||||
}
|
||||
|
||||
/// The model's partitions as cuts of the geometry.
|
||||
fn cuts(model: &Model) -> Vec<Cut> {
|
||||
model
|
||||
.partitions()
|
||||
.iter()
|
||||
.filter_map(|p| {
|
||||
let (point, normal) = model.datum(&p.datum)?.plane()?;
|
||||
Some(Cut { name: p.name.clone(), point, normal, bodies: p.bodies.clone() })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `design` cut by `model`'s partitions (the design as opened when the model has none).
|
||||
pub(crate) fn partitioned(design: &Design, model: &Model) -> Result<Design> {
|
||||
Ok(design.partitioned(&cuts(model))?)
|
||||
}
|
||||
|
||||
/// Cut the session's design by its model's partitions again.
|
||||
fn recut(s: &mut Session) -> Result<()> {
|
||||
if let Some(d) = &s.design {
|
||||
let cut = partitioned(d, &s.model)?;
|
||||
s.design = Some(Arc::new(cut));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn partition(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = super::name(p)?.to_string();
|
||||
let datum: String = super::req(p, "datum")?;
|
||||
let bodies: Vec<String> = super::opt(p, "bodies")?.unwrap_or_default();
|
||||
s.model.add_partition(Partition { name: name.clone(), datum: datum.clone(), bodies })?;
|
||||
recut(s)?;
|
||||
let design = s.design.as_deref().ok_or_else(|| EngineError::Params("open a design first".into()))?;
|
||||
let feature = format!("partition {name}");
|
||||
let errors: Vec<&str> = design.errors.iter().filter(|e| e.feature == feature).map(|e| e.message.as_str()).collect();
|
||||
if !errors.is_empty() {
|
||||
return Err(EngineError::Params(format!("partition `{name}`: {}", errors.join("; "))));
|
||||
}
|
||||
let report = design.cuts.iter().find(|c| c.name == name);
|
||||
let split = report.map(|r| r.split.clone()).unwrap_or_default();
|
||||
if split.is_empty() {
|
||||
return Err(EngineError::Params(format!("partition `{name}`: the plane divides no body of the design")));
|
||||
}
|
||||
let cells: Vec<String> = design.bodies.iter().map(|b| b.name.clone()).filter(|b| split.iter().any(|x| b.starts_with(&format!("{x}/")))).collect();
|
||||
let (faces, bodies): (usize, Vec<String>) = (report.map_or(0, |r| r.faces), design.bodies.iter().map(|b| b.name.clone()).collect());
|
||||
// The cut shows as edges on the cells, so the plane steps out of the way (view state, #295):
|
||||
// selecting it in the browser or its eye shows it again.
|
||||
if s.view.hidden.len() < MAX_HIDDEN {
|
||||
s.view.hidden.insert(Item { kind: ItemKind::Datum, name: datum });
|
||||
}
|
||||
Ok(json!({
|
||||
"name": name,
|
||||
"split": split,
|
||||
"cells": cells,
|
||||
"cut_faces": faces,
|
||||
"bodies": bodies,
|
||||
}))
|
||||
}
|
||||
|
||||
fn partition_delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = super::name(p)?;
|
||||
s.model.remove_partition(name)?;
|
||||
recut(s)?;
|
||||
let bodies: Vec<String> = s.design.iter().flat_map(|d| d.bodies.iter().map(|b| b.name.clone())).collect();
|
||||
Ok(json!({"deleted": name, "bodies": bodies}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A session with the sample plate (40 × 30 × 10, Ø10 hole at (15, 15)) open.
|
||||
pub(crate) fn plate() -> (Session, std::path::PathBuf) {
|
||||
let dir = std::env::temp_dir().join(format!("fieldcraft-partition-{}-{:?}", std::process::id(), std::thread::current().id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("plate.solidcraft");
|
||||
let plate = fieldcraft_geometry::sample::Plate::default();
|
||||
std::fs::write(&path, fieldcraft_geometry::sample::plate_design(&plate).unwrap()).unwrap();
|
||||
let mut s = Session::default();
|
||||
s.execute("geometry.open", &json!({"path": path.to_str().unwrap()})).unwrap();
|
||||
(s, dir)
|
||||
}
|
||||
|
||||
fn bodies(s: &Session) -> Vec<String> {
|
||||
s.design.as_ref().unwrap().bodies.iter().map(|b| b.name.clone()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn datums_by_each_definition() {
|
||||
let mut s = Session::default();
|
||||
let r = s.execute("geometry.datum", &json!({"name": "Mid", "by": {"type": "offset", "plane": "yz", "offset": 15}})).unwrap();
|
||||
assert_eq!(r, json!({"name": "Mid", "type": "plane", "point": [15.0, 0.0, 0.0], "normal": [1.0, 0.0, 0.0]}));
|
||||
let r = s
|
||||
.execute("geometry.datum", &json!({"name": "Tri", "by": {"type": "three_points", "a": [0, 0, 1], "b": [1, 0, 1], "c": [0, 1, 1]}}))
|
||||
.unwrap();
|
||||
assert_eq!(r["normal"], json!([0.0, 0.0, 1.0]));
|
||||
s.execute("geometry.datum", &json!({"name": "Tilt", "by": {"type": "point_normal", "point": [0, 0, 0], "normal": [0, 3, 4]}})).unwrap();
|
||||
assert_eq!(s.model.datum("Tilt"), Some(&Datum::Plane { point: [0.0; 3], normal: [0.0, 0.6, 0.8] }));
|
||||
let r = s.execute("geometry.datum.axis", &json!({"name": "Z", "by": {"type": "principal", "axis": "z", "through": [1, 2, 0]}})).unwrap();
|
||||
assert_eq!(r, json!({"name": "Z", "type": "axis", "point": [1.0, 2.0, 0.0], "direction": [0.0, 0.0, 1.0]}));
|
||||
s.execute("geometry.datum.axis", &json!({"name": "D", "by": {"type": "two_points", "a": [0, 0, 0], "b": [0, 2, 0]}})).unwrap();
|
||||
s.execute("geometry.datum.axis", &json!({"name": "E", "by": {"type": "point_direction", "point": [0, 0, 0], "direction": [5, 0, 0]}}))
|
||||
.unwrap();
|
||||
assert_eq!(s.model.datums().len(), 6);
|
||||
s.execute("geometry.datum.delete", &json!({"name": "D"})).unwrap();
|
||||
assert_eq!(s.model.datums().len(), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_datum_params_change_nothing() {
|
||||
let mut s = Session::default();
|
||||
for p in [
|
||||
json!({}),
|
||||
json!({"name": "A"}),
|
||||
json!({"name": "A", "by": {"type": "offset", "plane": "ab"}}),
|
||||
json!({"name": "A", "by": {"type": "offset", "plane": "xy", "offset": "x"}}),
|
||||
json!({"name": "A", "by": {"type": "three_points", "a": [0, 0, 0], "b": [1, 1, 1], "c": [2, 2, 2]}}),
|
||||
json!({"name": "A", "by": {"type": "point_normal", "point": [0, 0, 0], "normal": [0, 0, 0]}}),
|
||||
json!({"name": "A", "by": {"type": "point_normal", "point": [1e300, 0, 0], "normal": [0, 0, 1]}}),
|
||||
json!({"name": "A", "by": {"type": "point_normal", "point": [0, 0, 0], "normal": [0, 0, 1], "extra": 1}}),
|
||||
json!({"name": "1A", "by": {"type": "offset", "plane": "xy"}}),
|
||||
json!({"name": "A", "by": {"type": "nope"}}),
|
||||
] {
|
||||
assert!(s.execute("geometry.datum", &p).is_err(), "{p}");
|
||||
}
|
||||
for p in [
|
||||
json!({"name": "A", "by": {"type": "two_points", "a": [1, 1, 1], "b": [1, 1, 1]}}),
|
||||
json!({"name": "A", "by": {"type": "principal", "axis": "w"}}),
|
||||
] {
|
||||
assert!(s.execute("geometry.datum.axis", &p).is_err(), "{p}");
|
||||
}
|
||||
assert!(s.model.datums().is_empty());
|
||||
assert!(s.journal.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_partition_cuts_the_design_and_is_replayed_when_it_opens_again() {
|
||||
let (mut s, dir) = plate();
|
||||
s.execute("geometry.datum", &json!({"name": "Mid", "by": {"type": "offset", "plane": "yz", "offset": 15}})).unwrap();
|
||||
let r = s.execute("geometry.partition", &json!({"name": "Half", "datum": "Mid"})).unwrap();
|
||||
let body = r["split"][0].as_str().unwrap().to_string();
|
||||
assert_eq!(r["cells"], json!([format!("{body}/a"), format!("{body}/b")]));
|
||||
assert_eq!(r["cut_faces"], json!(4));
|
||||
// The datum is in use, and hidden: the cut shows as edges on the cells (#295). Its eye
|
||||
// shows it again.
|
||||
assert!(s.execute("geometry.datum.delete", &json!({"name": "Mid"})).is_err());
|
||||
assert!(!s.shows(ItemKind::Datum, "Mid"));
|
||||
s.execute("view.show", &json!({"items": [{"kind": "datum", "name": "Mid"}]})).unwrap();
|
||||
assert!(s.shows(ItemKind::Datum, "Mid"));
|
||||
s.execute("view.hide", &json!({"items": [{"kind": "datum", "name": "Mid"}]})).unwrap();
|
||||
|
||||
// A set on a cut face selects the cut face's pieces.
|
||||
let r = s.execute("geometry.bodies", &json!({})).unwrap();
|
||||
let faces: Vec<&str> = r[0]["faces"].as_array().unwrap().iter().map(|f| f["name"].as_str().unwrap()).collect();
|
||||
assert!(faces.contains(&"partition:Half:a#0"), "{faces:?}");
|
||||
|
||||
// Saved and opened again: the design is cut again by the model's partition.
|
||||
let file = dir.join("plate.fieldcraft");
|
||||
s.execute("file.save_as", &json!({"path": file.to_str().unwrap()})).unwrap();
|
||||
let mut t = Session::default();
|
||||
t.execute("file.open", &json!({"path": file.to_str().unwrap()})).unwrap();
|
||||
assert_eq!(bodies(&t), bodies(&s));
|
||||
assert!(!t.shows(ItemKind::Datum, "Mid"), "still hidden when opened again");
|
||||
// geometry.open again keeps the model, so its partition.
|
||||
let design = dir.join("plate.solidcraft");
|
||||
let r = t.execute("geometry.open", &json!({"path": design.to_str().unwrap()})).unwrap();
|
||||
assert_eq!(r["bodies"], json!(bodies(&s)));
|
||||
// A new model drops the partitions with the rest of the model.
|
||||
let r = t.execute("geometry.open", &json!({"path": design.to_str().unwrap(), "model": "new"})).unwrap();
|
||||
assert_eq!(r["bodies"], json!([body]));
|
||||
|
||||
// Undo brings the whole design back; deleting the partition does too.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(bodies(&s), std::slice::from_ref(&body));
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(bodies(&s).len(), 2);
|
||||
s.execute("geometry.partition.delete", &json!({"name": "Half"})).unwrap();
|
||||
assert_eq!(bodies(&s), [body]);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn datum_points_by_each_definition_and_planes_and_axes_through_them() {
|
||||
let (mut s, dir) = plate();
|
||||
let point = |s: &Session, n: &str| s.model.datum(n).and_then(Datum::point).unwrap();
|
||||
let close = |a: [f64; 3], b: [f64; 3]| a.iter().zip(&b).all(|(x, y)| (x - y).abs() < 1e-6);
|
||||
s.execute("geometry.datum.point", &json!({"name": "O", "by": {"type": "coordinates", "point": [0, 0, 0]}})).unwrap();
|
||||
s.execute("geometry.datum.point", &json!({"name": "X", "by": {"type": "coordinates", "point": [10, 0, 0]}})).unwrap();
|
||||
s.execute("geometry.datum.point", &json!({"name": "Y", "by": {"type": "coordinates", "point": [0, 10, 0]}})).unwrap();
|
||||
// The plate's edge along x at y = 0, z = 0, its midpoint and a quarter along it.
|
||||
let body = s.design.as_ref().unwrap().bodies[0].clone();
|
||||
let edge = body.edges().unwrap().into_iter().find(|e| e.points.iter().all(|p| p[1].abs() < 1e-9 && p[2].abs() < 1e-9)).unwrap();
|
||||
let by = |fraction: f64| json!({"type": "edge", "body": body.name, "edge": edge.name, "fraction": fraction});
|
||||
s.execute("geometry.datum.point", &json!({"name": "Mid", "by": {"type": "edge", "body": body.name, "edge": edge.name}})).unwrap();
|
||||
assert!(close(point(&s, "Mid"), [20.0, 0.0, 0.0]), "{:?}", point(&s, "Mid"));
|
||||
s.execute("geometry.datum.point", &json!({"name": "Q", "by": by(0.25)})).unwrap();
|
||||
let q = point(&s, "Q");
|
||||
assert!((q[0] - 10.0).abs() < 1e-6 || (q[0] - 30.0).abs() < 1e-6, "{q:?}");
|
||||
// The centre of the face at x = 0.
|
||||
let side =
|
||||
body.face_surfaces().unwrap().iter().position(
|
||||
|f| matches!(f, Some(fieldcraft_geometry::FaceSurface::Plane { normal, point }) if normal[0] < -0.5 && point[0].abs() < 1e-9),
|
||||
);
|
||||
let face = body.faces()[side.unwrap()].name.clone();
|
||||
s.execute("geometry.datum.point", &json!({"name": "C", "by": {"type": "face_centre", "body": body.name, "face": face}})).unwrap();
|
||||
assert!(close(point(&s, "C"), [0.0, 15.0, 5.0]), "{:?}", point(&s, "C"));
|
||||
|
||||
// Planes and axes through datum points; a point where an axis crosses a plane.
|
||||
let r = s.execute("geometry.datum", &json!({"name": "Base", "by": {"type": "datum_points", "a": "O", "b": "X", "c": "Y"}})).unwrap();
|
||||
assert_eq!(r["normal"], json!([0.0, 0.0, 1.0]));
|
||||
s.execute("geometry.datum.axis", &json!({"name": "Ax", "by": {"type": "datum_points", "a": "O", "b": "X"}})).unwrap();
|
||||
assert_eq!(s.model.datum("Ax"), Some(&Datum::Axis { point: [0.0; 3], direction: [1.0, 0.0, 0.0] }));
|
||||
s.execute("geometry.datum", &json!({"name": "Cut", "by": {"type": "normal_to_axis", "axis": "Ax", "point": "Mid"}})).unwrap();
|
||||
assert_eq!(s.model.datum("Cut"), Some(&Datum::Plane { point: point(&s, "Mid"), normal: [1.0, 0.0, 0.0] }));
|
||||
s.execute("geometry.datum.point", &json!({"name": "Hit", "by": {"type": "axis_plane", "axis": "Ax", "plane": "Cut"}})).unwrap();
|
||||
assert!(close(point(&s, "Hit"), [20.0, 0.0, 0.0]));
|
||||
|
||||
let journal = s.journal.len();
|
||||
for p in [
|
||||
json!({"name": "Z", "by": {"type": "axis_plane", "axis": "Ax", "plane": "Base"}}),
|
||||
json!({"name": "Z", "by": {"type": "axis_plane", "axis": "Base", "plane": "Cut"}}),
|
||||
json!({"name": "Z", "by": {"type": "edge", "body": body.name, "edge": edge.name, "fraction": 2}}),
|
||||
json!({"name": "Z", "by": {"type": "edge", "body": body.name, "edge": "nope"}}),
|
||||
json!({"name": "Z", "by": {"type": "edge", "body": "Nope", "edge": edge.name}}),
|
||||
json!({"name": "Z", "by": {"type": "face_centre", "body": body.name, "face": "nope"}}),
|
||||
// No mesh: no vertex is named.
|
||||
json!({"name": "Z", "by": {"type": "vertex", "body": body.name, "vertex": "v1"}}),
|
||||
json!({"name": "Z", "by": {"type": "coordinates", "point": [f64::MAX, 0, 0]}}),
|
||||
json!({"name": "Z", "by": {"type": "coordinates", "point": [0, 0]}}),
|
||||
] {
|
||||
assert!(s.execute("geometry.datum.point", &p).is_err(), "{p}");
|
||||
}
|
||||
for (command, p) in [
|
||||
("geometry.datum", json!({"name": "Z", "by": {"type": "datum_points", "a": "O", "b": "X", "c": "Mid"}})),
|
||||
("geometry.datum", json!({"name": "Z", "by": {"type": "datum_points", "a": "O", "b": "X", "c": "Ax"}})),
|
||||
("geometry.datum", json!({"name": "Z", "by": {"type": "normal_to_axis", "axis": "Nope"}})),
|
||||
("geometry.datum.axis", json!({"name": "Z", "by": {"type": "datum_points", "a": "O", "b": "O"}})),
|
||||
] {
|
||||
assert!(s.execute(command, &p).is_err(), "{p}");
|
||||
}
|
||||
assert_eq!(s.journal.len(), journal);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vertex_point_is_at_the_tagged_mesh_node() {
|
||||
let mut s = Session::default();
|
||||
s.execute(
|
||||
"mesh.block",
|
||||
&json!({"body": "Bar", "kind": "hex8", "corners": [[0,0,0],[4,0,0],[4,1,0],[0,1,0],[0,0,1],[4,0,1],[4,1,1],[0,1,1]], "divisions": [2, 1, 1], "vertices": {"7": "tip"}}),
|
||||
)
|
||||
.unwrap();
|
||||
s.execute("geometry.datum.point", &json!({"name": "Tip", "by": {"type": "vertex", "body": "Bar", "vertex": "tip"}})).unwrap();
|
||||
assert_eq!(s.model.datum("Tip").and_then(Datum::point), Some([4.0, 1.0, 1.0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editing_and_deleting_datums_follow_their_partitions() {
|
||||
let (mut s, dir) = plate();
|
||||
s.execute("geometry.datum", &json!({"name": "Mid", "by": {"type": "offset", "plane": "yz", "offset": 15}})).unwrap();
|
||||
s.execute("geometry.datum.axis", &json!({"name": "Ax", "by": {"type": "principal", "axis": "x"}})).unwrap();
|
||||
s.execute("geometry.partition", &json!({"name": "Half", "datum": "Mid"})).unwrap();
|
||||
let cut_at = |s: &Session| s.design.as_ref().unwrap().bodies[0].measure().unwrap().bbox_max[0];
|
||||
assert!((cut_at(&s) - 15.0).abs() < 1e-6);
|
||||
|
||||
// Moving the plane cuts again; an edit of the wrong kind or to an axis is refused.
|
||||
s.execute("geometry.datum.edit", &json!({"name": "Mid", "by": {"type": "offset", "plane": "yz", "offset": 25}})).unwrap();
|
||||
assert!((cut_at(&s) - 25.0).abs() < 1e-6);
|
||||
assert!(s.execute("geometry.datum.axis.edit", &json!({"name": "Mid", "by": {"type": "principal", "axis": "y"}})).is_err());
|
||||
assert!(s.execute("geometry.datum.edit", &json!({"name": "Ax", "by": {"type": "offset", "plane": "xy"}})).is_err());
|
||||
s.execute("geometry.datum.axis.edit", &json!({"name": "Ax", "by": {"type": "principal", "axis": "y"}})).unwrap();
|
||||
assert_eq!(s.model.datum("Ax"), Some(&Datum::Axis { point: [0.0; 3], direction: [0.0, 1.0, 0.0] }));
|
||||
|
||||
// The edit commands take the parameters edit_params gives back.
|
||||
for name in ["Mid", "Ax"] {
|
||||
let (command, params) = edit_params(name, s.model.datum(name).unwrap());
|
||||
s.execute(command, ¶ms).unwrap();
|
||||
}
|
||||
|
||||
// Deleting the plane names its partition, or deletes it too.
|
||||
let e = s.execute("geometry.datum.delete", &json!({"name": "Mid"})).unwrap_err().to_string();
|
||||
assert!(e.contains("partition `Half`"), "{e}");
|
||||
let r = s.execute("geometry.datum.delete", &json!({"name": "Mid", "cascade": true})).unwrap();
|
||||
assert_eq!(r["partitions"], json!(["Half"]));
|
||||
assert!(s.model.partitions().is_empty() && s.model.datum("Mid").is_none());
|
||||
assert_eq!(bodies(&s).len(), 1);
|
||||
// One undo step brings both back.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!((s.model.partitions().len(), bodies(&s).len()), (1, 2));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_partition_that_cuts_nothing_changes_nothing() {
|
||||
let (mut s, dir) = plate();
|
||||
s.execute("geometry.datum", &json!({"name": "Out", "by": {"type": "offset", "plane": "yz", "offset": 100}})).unwrap();
|
||||
s.execute("geometry.datum.axis", &json!({"name": "Ax", "by": {"type": "principal", "axis": "x"}})).unwrap();
|
||||
let journal = s.journal.len();
|
||||
for p in [
|
||||
json!({"name": "P", "datum": "Out"}),
|
||||
json!({"name": "P", "datum": "Ax"}),
|
||||
json!({"name": "P", "datum": "Nope"}),
|
||||
json!({"name": "P", "datum": "Out", "bodies": ["Nope"]}),
|
||||
json!({"name": "P", "datum": "Out", "bodies": "x"}),
|
||||
json!({"name": "", "datum": "Out"}),
|
||||
] {
|
||||
assert!(s.execute("geometry.partition", &p).is_err(), "{p}");
|
||||
}
|
||||
assert!(s.model.partitions().is_empty());
|
||||
assert_eq!(bodies(&s).len(), 1);
|
||||
assert_eq!(s.journal.len(), journal);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ use fieldcraft_io::roots::Access;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::req;
|
||||
use crate::requirement::Requirement;
|
||||
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
|
||||
|
||||
pub const WRITE: CommandSpec = CommandSpec {
|
||||
@@ -14,6 +15,7 @@ pub const WRITE: CommandSpec = CommandSpec {
|
||||
params: r#"{"format": "abaqus|nastran|lsdyna", "path": "part.inp", "steps": ["Load"]} — writes the model as a solver deck (formats: fieldcraft_decks::FORMATS); `steps` (optional) writes only those steps, as a Nastran run needs (static or frequency steps, not both); LS-DYNA writes several steps as *CASE analyses (run it with CASE); fails naming every error of the model check and everything the format cannot express"#,
|
||||
form: Some(super::forms::DECK),
|
||||
kind: CommandKind::Session,
|
||||
requires: &[Requirement::Analysable, Requirement::ElementMaterial, Requirement::ElementSection],
|
||||
run: write,
|
||||
};
|
||||
|
||||
@@ -60,7 +62,7 @@ mod tests {
|
||||
assert!(s.execute("deck.write", &json!({"path": other})).is_err());
|
||||
assert!(s.execute("deck.write", &json!({"format": "abaqus"})).is_err());
|
||||
let mut empty = Session::default();
|
||||
assert!(matches!(empty.execute("deck.write", &json!({"format": "abaqus", "path": other})), Err(EngineError::Deck(_))));
|
||||
assert!(matches!(empty.execute("deck.write", &json!({"format": "abaqus", "path": other})), Err(EngineError::Unavailable(_))));
|
||||
assert!(!dir.join("other.inp").exists());
|
||||
assert!(matches!(s.execute("deck.write", &json!({"format": "abaqus", "path": dir.to_string_lossy()})), Err(EngineError::File(_))));
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ use serde::de::DeserializeOwned;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{name, opt, req};
|
||||
use crate::requirement::Requirement;
|
||||
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
|
||||
|
||||
/// The parameters other than `name`, read as a definition's JSON form.
|
||||
@@ -26,13 +27,14 @@ fn fields<T: DeserializeOwned>(p: &Value, what: &str) -> Result<T> {
|
||||
/// Create, edit and delete commands for one kind of definition.
|
||||
macro_rules! definition_commands {
|
||||
($what:literal, $ty:ty, $id:literal, $label:literal, $doc:literal, $form:expr, $delete_form:expr, $add:ident, $replace:ident, $remove:ident,
|
||||
$CREATE:ident, $EDIT:ident, $DELETE:ident) => {
|
||||
$CREATE:ident, $EDIT:ident, $DELETE:ident, requires: $requires:expr, exists: $exists:ident) => {
|
||||
pub const $CREATE: CommandSpec = CommandSpec {
|
||||
id: concat!("model.", $id, ".create"),
|
||||
label: concat!("New ", $label),
|
||||
params: concat!($doc, " — fails if the name is taken"),
|
||||
form: Some($form),
|
||||
kind: CommandKind::Model,
|
||||
requires: $requires,
|
||||
run: |s: &mut Session, p: &Value| {
|
||||
let n = name(p)?;
|
||||
s.model.$add(n, fields::<$ty>(p, $what)?)?;
|
||||
@@ -45,6 +47,7 @@ macro_rules! definition_commands {
|
||||
params: concat!($doc, " — replaces the existing definition of that name"),
|
||||
form: Some($form),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::$exists],
|
||||
run: |s: &mut Session, p: &Value| {
|
||||
let n = name(p)?;
|
||||
s.model.$replace(n, fields::<$ty>(p, $what)?)?;
|
||||
@@ -57,6 +60,7 @@ macro_rules! definition_commands {
|
||||
params: r#"{"name": "…"} — refused while another definition refers to it"#,
|
||||
form: Some($delete_form),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::$exists],
|
||||
run: |s: &mut Session, p: &Value| {
|
||||
s.model.$remove(name(p)?)?;
|
||||
Ok(Value::Null)
|
||||
@@ -78,7 +82,9 @@ definition_commands!(
|
||||
remove_set,
|
||||
SET_CREATE,
|
||||
SET_EDIT,
|
||||
SET_DELETE
|
||||
SET_DELETE,
|
||||
requires: &[],
|
||||
exists: Set
|
||||
);
|
||||
|
||||
definition_commands!(
|
||||
@@ -94,7 +100,9 @@ definition_commands!(
|
||||
remove_material,
|
||||
MATERIAL_CREATE,
|
||||
MATERIAL_EDIT,
|
||||
MATERIAL_DELETE
|
||||
MATERIAL_DELETE,
|
||||
requires: &[],
|
||||
exists: Material
|
||||
);
|
||||
|
||||
/// A copy of material `name` with `change` applied, put back through the model's validation.
|
||||
@@ -112,6 +120,7 @@ pub const MATERIAL_PLASTICITY: CommandSpec = CommandSpec {
|
||||
params: r#"{"name": "Steel", "plastic": {"type": "bilinear", "yield_stress": 250, "hardening_modulus": 1000, "hardening": "isotropic|kinematic"} | {"type": "table", "points": [{"strain": 0, "stress": 250}, {"strain": 0.1, "stress": 300}]} | {"type": "johnson_cook", "a": 792, "b": 510, "n": 0.26, "c": 0.014, "m": 1.03, "reference_strain_rate": 1, "room_temperature": 294, "melt_temperature": 1793, "specific_heat": 4.77e8, "taylor_quinney": 0.9} | null} — von Mises plasticity of an isotropic material (null removes it); explicit dynamics uses it, the linear solver the elastic constants alone"#,
|
||||
form: Some(super::forms::MATERIAL_PLASTICITY),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Material],
|
||||
run: |s: &mut Session, p: &Value| {
|
||||
change_material(s, p, |m, p| {
|
||||
m.plastic = req(p, "plastic")?;
|
||||
@@ -126,6 +135,7 @@ pub const MATERIAL_DAMAGE: CommandSpec = CommandSpec {
|
||||
params: r#"{"name": "Steel", "damage": {"type": "johnson_cook", "d1": 0.05, "d2": 3.44, "d3": -2.12, "d4": 0.002, "d5": 0.61} | null, "erosion": {"plastic_strain": 1.0} | null} — damage to failure and element erosion of a plastic material (each key optional; null removes it); a failed element is eroded in explicit dynamics"#,
|
||||
form: Some(super::forms::MATERIAL_DAMAGE),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Material],
|
||||
run: |s: &mut Session, p: &Value| {
|
||||
change_material(s, p, |m, p| {
|
||||
// Absent leaves a field as it is; null removes it.
|
||||
@@ -157,7 +167,9 @@ definition_commands!(
|
||||
remove_section,
|
||||
SECTION_CREATE,
|
||||
SECTION_EDIT,
|
||||
SECTION_DELETE
|
||||
SECTION_DELETE,
|
||||
requires: &[Requirement::Material, Requirement::Set],
|
||||
exists: Section
|
||||
);
|
||||
|
||||
definition_commands!(
|
||||
@@ -173,7 +185,9 @@ definition_commands!(
|
||||
remove_reference_point,
|
||||
REFERENCE_POINT_CREATE,
|
||||
REFERENCE_POINT_EDIT,
|
||||
REFERENCE_POINT_DELETE
|
||||
REFERENCE_POINT_DELETE,
|
||||
requires: &[],
|
||||
exists: ReferencePoint
|
||||
);
|
||||
|
||||
definition_commands!(
|
||||
@@ -189,7 +203,9 @@ definition_commands!(
|
||||
remove_coupling,
|
||||
COUPLING_CREATE,
|
||||
COUPLING_EDIT,
|
||||
COUPLING_DELETE
|
||||
COUPLING_DELETE,
|
||||
requires: &[Requirement::ReferencePoint, Requirement::Set],
|
||||
exists: Coupling
|
||||
);
|
||||
|
||||
definition_commands!(
|
||||
@@ -205,7 +221,9 @@ definition_commands!(
|
||||
remove_mass,
|
||||
MASS_CREATE,
|
||||
MASS_EDIT,
|
||||
MASS_DELETE
|
||||
MASS_DELETE,
|
||||
requires: &[Requirement::Target],
|
||||
exists: Mass
|
||||
);
|
||||
|
||||
definition_commands!(
|
||||
@@ -221,7 +239,9 @@ definition_commands!(
|
||||
remove_spring,
|
||||
SPRING_CREATE,
|
||||
SPRING_EDIT,
|
||||
SPRING_DELETE
|
||||
SPRING_DELETE,
|
||||
requires: &[Requirement::Target],
|
||||
exists: Spring
|
||||
);
|
||||
|
||||
definition_commands!(
|
||||
@@ -237,7 +257,9 @@ definition_commands!(
|
||||
remove_boundary_condition,
|
||||
BOUNDARY_CONDITION_CREATE,
|
||||
BOUNDARY_CONDITION_EDIT,
|
||||
BOUNDARY_CONDITION_DELETE
|
||||
BOUNDARY_CONDITION_DELETE,
|
||||
requires: &[Requirement::Target],
|
||||
exists: BoundaryCondition
|
||||
);
|
||||
|
||||
definition_commands!(
|
||||
@@ -253,7 +275,9 @@ definition_commands!(
|
||||
remove_load,
|
||||
LOAD_CREATE,
|
||||
LOAD_EDIT,
|
||||
LOAD_DELETE
|
||||
LOAD_DELETE,
|
||||
requires: &[],
|
||||
exists: Load
|
||||
);
|
||||
|
||||
definition_commands!(
|
||||
@@ -269,7 +293,9 @@ definition_commands!(
|
||||
remove_fluid_domain,
|
||||
FLUID_DOMAIN_CREATE,
|
||||
FLUID_DOMAIN_EDIT,
|
||||
FLUID_DOMAIN_DELETE
|
||||
FLUID_DOMAIN_DELETE,
|
||||
requires: &[Requirement::Material],
|
||||
exists: FluidDomain
|
||||
);
|
||||
|
||||
pub const FLUID_BOUNDARY: CommandSpec = CommandSpec {
|
||||
@@ -278,6 +304,7 @@ pub const FLUID_BOUNDARY: CommandSpec = CommandSpec {
|
||||
params: r#"{"domain": "Flow", "at": "x_min" (a box face) | {"body": "Body1", "face": "F2:top"} (an obstacle face), "condition": {"type": "velocity", "velocity": [u, v, w], "profile": "uniform|parabolic"} | {"type": "pressure", "pressure": 0} | {"type": "wall"} | {"type": "moving_wall", "velocity": [u, v, w]} | {"type": "slip"} | {"type": "periodic"}} — sets one boundary's condition (obstacle faces take walls and moving walls)"#,
|
||||
form: Some(super::forms::FLUID_BOUNDARY),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::FluidDomain],
|
||||
run: fluid_boundary,
|
||||
};
|
||||
|
||||
@@ -295,6 +322,7 @@ pub const STEP_CREATE: CommandSpec = CommandSpec {
|
||||
params: r#"{"name": "Bend", "procedure": {"type": "static"} | {"type": "nonlinear_static", "nonlinear_geometry": true, "initial_increment": 0.1, "min_increment": 1e-5, "max_increment": 1.0 (fractions of the step), "max_increments": 100, "max_iterations": 16 (per increment), "tolerances": {"force": 1e-6, "displacement": 1e-5, "energy": 1e-10}, "line_search": false, "load_path": [[0, 0], [0.5, 1], [1, 0]] (optional: the load factor against the step fraction, piecewise linear from [0, 0] to fraction 1; increments end at its points)} (loads and prescribed displacements are the load factor times their values; it ramps from 0 to 1 without a load path) | {"type": "frequency", "modes": 10, "min_hz": 0, "max_hz": 500} | {"type": "fluid", "domain": "Flow", "end_time": 1.0 | "steps": 1000, "time_step": (default: chosen for Mach 0.087 and τ ≤ 1), "frames": 10, "magic": 0.1875 (the two-relaxation-time Λ)} | {"type": "explicit_dynamic", "end_time": 0.001, "dt_scale": 0.9, "max_increments": 10000000, "output_interval", "history_interval", "history_nodes": "set", "initial_velocities": [{"set", "velocity": [vx, vy, vz]}], "rigid_walls": [{"set", "point", "normal", "friction": {"static": 0.3, "kinetic": 0.2, "decay": 10} (Coulomb; default frictionless)}], "hourglass": {"type": "viscous|stiffness", "coefficient": 0.1}, "bulk_viscosity": {"linear": 0.06, "quadratic": 1.5}, "mass_scaling": {"target_increment": 1e-6, "set": "…" (optional, default every element)} (opt-in: elements below the target increment get the density that reaches it; the added mass is reported)}, "output": ["displacement", "reaction_force", "stress", "strain"] (default by procedure), "boundary_conditions": [names], "loads": [names] (active in this step; nothing carries over between steps), "before": "step" (default: last)}"#,
|
||||
form: Some(super::forms::STEP_CREATE),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[],
|
||||
run: step_create,
|
||||
};
|
||||
|
||||
@@ -304,6 +332,7 @@ pub const STEP_EDIT: CommandSpec = CommandSpec {
|
||||
params: r#"{"name": "Bend", "procedure", "output", "boundary_conditions", "loads"} — as model.step.create; what is left out keeps its value"#,
|
||||
form: Some(super::forms::STEP_EDIT),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Step],
|
||||
run: step_edit,
|
||||
};
|
||||
|
||||
@@ -313,6 +342,7 @@ pub const STEP_DELETE: CommandSpec = CommandSpec {
|
||||
params: r#"{"name": "Bend"}"#,
|
||||
form: Some(super::forms::STEP_DELETE),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Step],
|
||||
run: |s, p| s.model.remove_step(name(p)?).map(|_| Value::Null).map_err(Into::into),
|
||||
};
|
||||
|
||||
@@ -322,6 +352,7 @@ pub const STEP_ACTIVATE: CommandSpec = CommandSpec {
|
||||
params: r#"{"step": "Bend", "boundary_conditions": [names], "loads": [names], "active": true} — switches the listed items on (or off with false) in that step only"#,
|
||||
form: Some(super::forms::STEP_ACTIVATE),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Step],
|
||||
run: step_activate,
|
||||
};
|
||||
|
||||
@@ -331,6 +362,7 @@ pub const ACTIVITY: CommandSpec = CommandSpec {
|
||||
params: "{}",
|
||||
form: Some(&[]),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[],
|
||||
run: |s, _| Ok(activity(&s.model)),
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
//! Crash reports and bug report drafts (docs/crash-reports.md): list and read the reports the
|
||||
//! desktop app wrote, draft a bug report, and (with `FIELDCRAFT_CRASH_TEST=1`) crash on purpose
|
||||
//! to check that reporting works.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use fieldcraft_io::roots::Access;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{file_param, opt, req};
|
||||
use crate::{CommandKind, CommandSpec, EngineError, Result, Session, bug_report, crash};
|
||||
|
||||
pub const CRASH_REPORTS: CommandSpec = CommandSpec {
|
||||
id: "diagnostics.crash_reports",
|
||||
label: "Crash Reports",
|
||||
params: r#"{"limit"?: 20, "dir"?: "…"} — the crash reports the desktop app wrote on this computer, newest first: id, kind (command_panic, recovered_panic, panic, unclean_exit), time, message, command, count, version, path and whether it can be replayed (default folder: FIELDCRAFT_CRASH_DIR, a temporary folder in runs driven by automation, else the per-user data folder)"#,
|
||||
form: Some(super::forms::CRASH_REPORTS),
|
||||
kind: CommandKind::Session,
|
||||
requires: &[],
|
||||
run: crash_reports,
|
||||
};
|
||||
|
||||
pub const CRASH_REPORT: CommandSpec = CommandSpec {
|
||||
id: "diagnostics.crash_report",
|
||||
label: "Crash Report",
|
||||
params: r#"{"id": "20261014-101500-…", "dir"?: "…"} — one crash report: what happened, where, the backtrace, the command and recent commands, and the paths of its model, replay and log files"#,
|
||||
form: Some(super::forms::CRASH_REPORT),
|
||||
kind: CommandKind::Session,
|
||||
requires: &[],
|
||||
run: crash_report,
|
||||
};
|
||||
|
||||
pub const BUG_REPORT: CommandSpec = CommandSpec {
|
||||
id: "diagnostics.bug_report",
|
||||
label: "Report a Bug",
|
||||
params: r#"{"title"?: "…", "observed"?: "what happened", "crash"?: "<crash report id>", "share_session"?: false, "include_model"?: false} — drafts a GitHub bug report: the issue link (the bug form filled with the version, the OS, what happened and, for a crash, where), and the files to attach. Only with share_session does it carry the model's commands, and only with include_model as well the model file. Nothing is sent: the desktop app's Help › Report a Bug shows the draft and opens the link when the user asks"#,
|
||||
form: Some(super::forms::BUG_REPORT),
|
||||
kind: CommandKind::Session,
|
||||
requires: &[],
|
||||
run: bug_report_draft,
|
||||
};
|
||||
|
||||
pub const CRASH_TEST: CommandSpec = CommandSpec {
|
||||
id: "diagnostics.crash_test",
|
||||
label: "Crash Test",
|
||||
params: r#"{"mode": "panic|recovered|abort"} — crashes on purpose to check that crash reports work (only with FIELDCRAFT_CRASH_TEST=1): panic, an internal error in this command; recovered, one caught inside it; abort, the app ends at once (reported at its next start)"#,
|
||||
form: Some(super::forms::CRASH_TEST),
|
||||
kind: CommandKind::Session,
|
||||
requires: &[],
|
||||
run: crash_test,
|
||||
};
|
||||
|
||||
fn crash_dir(s: &Session, p: &Value) -> Result<PathBuf> {
|
||||
if p.get("dir").is_some() {
|
||||
return Ok(PathBuf::from(file_param(s, p, "dir", Access::Read)?));
|
||||
}
|
||||
crash::default_dir().ok_or_else(|| EngineError::Params("no crash folder: set FIELDCRAFT_CRASH_DIR or give `dir`".into()))
|
||||
}
|
||||
|
||||
fn crash_reports(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let dir = crash_dir(s, p)?;
|
||||
let limit = opt::<usize>(p, "limit")?.unwrap_or(crash::MAX_REPORTS);
|
||||
let mut reports = crash::list(&dir);
|
||||
reports.truncate(limit);
|
||||
Ok(json!({"dir": dir.to_string_lossy(), "reports": reports}))
|
||||
}
|
||||
|
||||
fn crash_report(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let dir = crash_dir(s, p)?;
|
||||
let id = req::<String>(p, "id")?;
|
||||
crash::read(&dir, &id).map_err(EngineError::Params)
|
||||
}
|
||||
|
||||
/// The draft input for `p` from the session: its commands and model (when shared), or a crash
|
||||
/// report's replay and model.
|
||||
pub fn bug_report_input(s: &Session, p: &Value) -> Result<bug_report::Input> {
|
||||
let share = opt::<bool>(p, "share_session")?.unwrap_or(false);
|
||||
let include_model = opt::<bool>(p, "include_model")?.unwrap_or(false);
|
||||
let mut input = bug_report::Input {
|
||||
title: opt::<String>(p, "title")?.unwrap_or_default(),
|
||||
observed: opt::<String>(p, "observed")?.unwrap_or_default(),
|
||||
share_session: share,
|
||||
include_model,
|
||||
..Default::default()
|
||||
};
|
||||
match opt::<String>(p, "crash")? {
|
||||
Some(id) => {
|
||||
let report = crash::read(&crash_dir(s, p)?, &id).map_err(EngineError::Params)?;
|
||||
if share {
|
||||
let read = |k: &str| {
|
||||
report
|
||||
.get(k)
|
||||
.and_then(Value::as_str)
|
||||
.and_then(|f| fieldcraft_io::fs::read_capped(std::path::Path::new(f), crash::MAX_MODEL_BYTES as u64).ok())
|
||||
};
|
||||
let replay: Value = read("replay_path").and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or(Value::Null);
|
||||
input.commands = replay.get("commands").and_then(Value::as_array).cloned().unwrap_or_default();
|
||||
input.model = if include_model { read("model_path") } else { None };
|
||||
}
|
||||
input.crash = Some(report);
|
||||
}
|
||||
None if share => {
|
||||
input.commands = s.journal.iter().map(|(command, params)| json!({"command": command, "params": params})).collect();
|
||||
input.model = if include_model { Some(s.file_bytes(None)?) } else { None };
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
Ok(input)
|
||||
}
|
||||
|
||||
fn bug_report_draft(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let input = bug_report_input(s, p)?;
|
||||
Ok(bug_report::draft(&input, &crash::Build::current().version_line()).to_json())
|
||||
}
|
||||
|
||||
// The one deliberate panic and abort: they prove that crash reports work, and run only when
|
||||
// asked for with FIELDCRAFT_CRASH_TEST=1.
|
||||
#[allow(clippy::panic)]
|
||||
fn crash_test(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mode = req::<String>(p, "mode")?;
|
||||
if std::env::var_os("FIELDCRAFT_CRASH_TEST").is_none_or(|v| v != "1") {
|
||||
return Err(EngineError::Params("the crash test runs only with FIELDCRAFT_CRASH_TEST=1".into()));
|
||||
}
|
||||
match mode.as_str() {
|
||||
"panic" => std::panic::panic_any(String::from("crash test: an internal error in a command")),
|
||||
"recovered" => {
|
||||
let caught = std::panic::catch_unwind(|| std::panic::panic_any(String::from("crash test: an internal error caught inside a command")));
|
||||
Ok(json!({"caught": caught.is_err()}))
|
||||
}
|
||||
"abort" => std::process::abort(),
|
||||
_ => Err(EngineError::invalid("mode", "must be panic, recovered or abort")),
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,7 @@ pub const UNDO: CommandSpec = CommandSpec {
|
||||
params: r#"{"count"?: 1} — takes back the last command that changed the model (it leaves the journal and can be redone); `count` takes back that many, as far as the history reaches"#,
|
||||
form: Some(super::forms::COUNT),
|
||||
kind: CommandKind::Session,
|
||||
requires: &[],
|
||||
run: |s, p| repeat(s, p, Session::undo),
|
||||
};
|
||||
|
||||
@@ -47,6 +48,7 @@ pub const REDO: CommandSpec = CommandSpec {
|
||||
params: r#"{"count"?: 1} — runs the last undone command's change again; `count` redoes that many, as far as there are undone commands"#,
|
||||
form: Some(super::forms::COUNT),
|
||||
kind: CommandKind::Session,
|
||||
requires: &[],
|
||||
run: |s, p| repeat(s, p, Session::redo),
|
||||
};
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ pub const OPEN: CommandSpec = CommandSpec {
|
||||
params: r#"{"path": "bracket.fieldcraft"} — opens the model, its mesh and its journal, and opens its design and imported meshes again from their files (one that is missing or changed is listed in `warnings`; the model still opens); unsaved changes of the current model are discarded and the undo history starts empty"#,
|
||||
form: Some(super::forms::FILE_OPEN),
|
||||
kind: CommandKind::Session,
|
||||
requires: &[],
|
||||
run: open,
|
||||
};
|
||||
|
||||
@@ -34,6 +35,7 @@ pub const SAVE: CommandSpec = CommandSpec {
|
||||
params: r#"{"path"?: "bracket.fieldcraft"} — saves to `path`, else to the file the model was opened from or last saved to; written atomically, the previous version kept as `<file>.bak`"#,
|
||||
form: Some(super::forms::FILE_SAVE),
|
||||
kind: CommandKind::Session,
|
||||
requires: &[],
|
||||
run: save,
|
||||
};
|
||||
|
||||
@@ -43,15 +45,17 @@ pub const SAVE_AS: CommandSpec = CommandSpec {
|
||||
params: r#"{"path": "bracket.fieldcraft"} — saves to a new file, which becomes the model's file"#,
|
||||
form: Some(super::forms::FILE_SAVE_AS),
|
||||
kind: CommandKind::Session,
|
||||
requires: &[],
|
||||
run: save_as,
|
||||
};
|
||||
|
||||
pub const RECOVERY_LIST: CommandSpec = CommandSpec {
|
||||
id: "file.recovery.list",
|
||||
label: "Recoverable Models",
|
||||
params: r#"{"dir"?: "…"} — models autosaved by apps that crashed or closed with unsaved changes, newest first (default folder: FIELDCRAFT_RECOVERY_DIR or the per-user data folder)"#,
|
||||
params: r#"{"dir"?: "…"} — models autosaved by apps that crashed or closed with unsaved changes, newest first, each with its id, path, saved_at, age (seconds) and node and element counts (default folder: FIELDCRAFT_RECOVERY_DIR, a temporary folder in runs driven by automation, else the per-user data folder)"#,
|
||||
form: Some(super::forms::RECOVERY_LIST),
|
||||
kind: CommandKind::Session,
|
||||
requires: &[],
|
||||
run: recovery_list,
|
||||
};
|
||||
|
||||
@@ -61,6 +65,7 @@ pub const RECOVER: CommandSpec = CommandSpec {
|
||||
params: r#"{"id": "…", "dir"?: "…"} — opens an autosaved model (an id from file.recovery.list) with its original file path, as unsaved changes; the autosave stays until file.recovery.discard"#,
|
||||
form: Some(super::forms::RECOVER),
|
||||
kind: CommandKind::Session,
|
||||
requires: &[],
|
||||
run: recover,
|
||||
};
|
||||
|
||||
@@ -70,6 +75,7 @@ pub const RECOVERY_DISCARD: CommandSpec = CommandSpec {
|
||||
params: r#"{"id": "…"} or {"all": true}; "dir"?: "…" — deletes autosaves of apps that are no longer running"#,
|
||||
form: Some(super::forms::RECOVERY_DISCARD),
|
||||
kind: CommandKind::Session,
|
||||
requires: &[],
|
||||
run: recovery_discard,
|
||||
};
|
||||
|
||||
@@ -79,6 +85,7 @@ pub const SAMPLE: CommandSpec = CommandSpec {
|
||||
params: r#"{"name": "cantilever"} — opens a sample model (fieldcraft_engine::sample; the list is in docs/examples.md) in place of the current one, unsaved changes discarded; every sample but `parts` is ready to solve (solve.run)"#,
|
||||
form: Some(super::forms::SAMPLE),
|
||||
kind: CommandKind::Session,
|
||||
requires: &[],
|
||||
run: open_sample,
|
||||
};
|
||||
|
||||
@@ -90,11 +97,15 @@ fn open_sample(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(recipe) = sample.design {
|
||||
opened.design = Some(Arc::new(open_design(&fieldcraft_geometry::script_design(recipe)?)?));
|
||||
}
|
||||
if let Some(prepare) = sample.prepare {
|
||||
opened.run_script(&prepare())?;
|
||||
}
|
||||
let bodies = opened.design.as_ref().map_or(&[][..], |d| d.bodies.as_slice());
|
||||
let script = (sample.script)(bodies);
|
||||
opened.run_script(&script)?;
|
||||
// A sample just opened has nothing to save: it opens again the same way.
|
||||
opened.saved_revision = Some(opened.revision);
|
||||
opened.saved_view = opened.view.clone();
|
||||
s.replace_with(opened);
|
||||
let mut reply = summary(s, &[]);
|
||||
reply["sample"] = json!(sample.name);
|
||||
@@ -180,7 +191,7 @@ impl Session {
|
||||
design: self.sources.design.as_ref().map(stored).transpose()?,
|
||||
meshes: self.sources.meshes.iter().map(stored).collect::<fieldcraft_io::Result<_>>()?,
|
||||
};
|
||||
Ok(fieldcraft_io::write(&self.model, &geometry, &self.journal)?)
|
||||
Ok(fieldcraft_io::write(&self.model, &geometry, &self.journal, &self.view)?)
|
||||
}
|
||||
|
||||
/// A session holding what a file holds, its geometry opened again from the paths it names
|
||||
@@ -192,7 +203,16 @@ impl Session {
|
||||
let mut design: Option<Arc<Design>> = None;
|
||||
if let Some(stored) = &file.geometry.design {
|
||||
let (opened, source) = reopen("design", stored, base, roots, MAX_DESIGN_BYTES as u64, open_design, &mut warnings);
|
||||
design = opened.map(Arc::new);
|
||||
design = opened.and_then(|d| match super::datum::partitioned(&d, &file.model) {
|
||||
Ok(cut) => Some(Arc::new(cut)),
|
||||
Err(e) => {
|
||||
warnings.push(format!("the design's partitions could not be applied ({e}); the model opens without the design"));
|
||||
None
|
||||
}
|
||||
});
|
||||
if let Some(d) = &design {
|
||||
warnings.extend(d.errors.iter().filter(|e| e.feature.starts_with("partition ")).map(|e| format!("{}: {}", e.feature, e.message)));
|
||||
}
|
||||
sources.design = Some(source);
|
||||
}
|
||||
let mut surfaces = Vec::new();
|
||||
@@ -201,18 +221,30 @@ impl Session {
|
||||
surfaces.extend(opened.into_iter().flatten().map(Arc::new));
|
||||
sources.meshes.push(source);
|
||||
}
|
||||
let session =
|
||||
Session { model: file.model, design, surfaces, sources, journal: file.journal, revision: next_revision(), ..Session::default() };
|
||||
let session = Session {
|
||||
model: file.model,
|
||||
design,
|
||||
surfaces,
|
||||
sources,
|
||||
journal: file.journal,
|
||||
revision: next_revision(),
|
||||
saved_view: file.view.clone(),
|
||||
view: file.view,
|
||||
..Session::default()
|
||||
};
|
||||
(session, warnings)
|
||||
}
|
||||
|
||||
/// Replace this session with `opened`, keeping its undo memory limit, its work caps and its
|
||||
/// file access; the history starts empty.
|
||||
/// file access (and where its commands come from); the history starts empty.
|
||||
fn replace_with(&mut self, mut opened: Session) {
|
||||
opened.history = std::mem::take(&mut self.history);
|
||||
opened.limits = self.limits;
|
||||
opened.file_access = std::mem::take(&mut self.file_access);
|
||||
opened.crash_journal = self.crash_journal;
|
||||
opened.origin = self.origin;
|
||||
opened.clear_history();
|
||||
opened.mark_opened();
|
||||
*self = opened;
|
||||
}
|
||||
}
|
||||
@@ -288,8 +320,15 @@ fn recovery_dir(s: &Session, p: &Value, access: Access) -> Result<PathBuf> {
|
||||
}
|
||||
|
||||
fn recovery_list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let entries = fieldcraft_io::recovery::orphans(&recovery_dir(s, p, Access::Read)?);
|
||||
serde_json::to_value(entries).map_err(|e| EngineError::Params(e.to_string()))
|
||||
let mut listed = Vec::new();
|
||||
for e in fieldcraft_io::recovery::orphans(&recovery_dir(s, p, Access::Read)?) {
|
||||
let mut v = serde_json::to_value(&e).map_err(|e| EngineError::Params(e.to_string()))?;
|
||||
if let Some(o) = v.as_object_mut() {
|
||||
o.insert("age".into(), json!(e.age()));
|
||||
}
|
||||
listed.push(v);
|
||||
}
|
||||
Ok(Value::Array(listed))
|
||||
}
|
||||
|
||||
fn recover(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -405,6 +444,9 @@ mod tests {
|
||||
refused(s.execute("file.recovery.discard", &json!({"all": true, "dir": input})));
|
||||
s.execute("geometry.open", &json!({"path": input.join("plate.solidcraft")})).unwrap();
|
||||
defined(&mut s);
|
||||
// A section, so deck.write has all it needs and reaches its path.
|
||||
s.execute("model.set.create", &json!({"name": "all", "elements": [1]})).unwrap();
|
||||
s.execute("model.section.create", &json!({"name": "solid", "set": "all", "material": "Steel", "kind": {"type": "solid"}})).unwrap();
|
||||
// Writes go to the write root only: not the read root, not elsewhere.
|
||||
refused(s.execute("file.save_as", &json!({"path": input.join("m.fieldcraft")})));
|
||||
refused(s.execute("file.save_as", &json!({"path": outside.join("m.fieldcraft")})));
|
||||
|
||||
@@ -1,28 +1,35 @@
|
||||
use crate::schema::ProblemKind;
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use fieldcraft_geometry::tagged_mesh;
|
||||
use fieldcraft_geometry::{MAX_DESIGN_BYTES, Shape, SurfaceMesh, open_design};
|
||||
use fieldcraft_geometry::{Design, MAX_DESIGN_BYTES, Shape, SurfaceMesh, open_design};
|
||||
use fieldcraft_io::SourceFile;
|
||||
use fieldcraft_io::roots::Access;
|
||||
use fieldcraft_model::Model;
|
||||
use fieldcraft_model::geometry::{Entity, GeometryRef};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::requirement::Requirement;
|
||||
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
|
||||
|
||||
pub const OPEN: CommandSpec = CommandSpec {
|
||||
id: "geometry.open",
|
||||
label: "Open Design",
|
||||
params: r#"{"path": "part.solidcraft"} — rebuilds the SolidCraft design and makes its bodies the geometry; opening it again after an edit picks up the change"#,
|
||||
params: r#"{"path": "part.solidcraft", "model"?: "keep"} — rebuilds the SolidCraft design and makes its bodies the geometry. `model`: "keep" (default) keeps the mesh and every definition, so opening the same design again after an edit picks up the change and sets follow their persistent face names; "new" starts a new model with the design (no mesh, sets, materials, sections, BCs, loads or steps; the unit system stays; the model is untitled until saved, and undo restores the previous file). The reply's `related` is false when the model (before the open) refers to bodies (mesh tags, set geometry) and the design has none of them, and `stale` lists what no longer resolves: `mesh_bodies` (bodies the mesh is tagged with that the design lacks) `sets` (sets naming a body or face it lacks) and `seeds` (edge seeds on edges it lacks). One undo step"#,
|
||||
form: Some(super::forms::OPEN_DESIGN),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[],
|
||||
run: open,
|
||||
};
|
||||
|
||||
pub const BODIES: CommandSpec = CommandSpec {
|
||||
id: "geometry.bodies",
|
||||
label: "Bodies",
|
||||
params: "{} — the open design's bodies: measures and persistent face names (by face index)",
|
||||
params: "{} — the open design's bodies: measures, persistent face names (by face index) and edges (persistent name `<face>|<face>`, `~k` when several separate the same faces, and length)",
|
||||
form: Some(&[]),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[], // No design is an answer too: no bodies.
|
||||
run: bodies,
|
||||
};
|
||||
|
||||
@@ -32,6 +39,7 @@ pub const TESSELLATE: CommandSpec = CommandSpec {
|
||||
params: r#"{"body": "Body1", "tolerance": 0.05} — triangulates the body's boundary within the chordal tolerance (mm); reports triangles per face"#,
|
||||
form: Some(super::forms::TESSELLATE),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Design],
|
||||
run: tessellate,
|
||||
};
|
||||
|
||||
@@ -41,29 +49,100 @@ pub const IMPORT_MESH: CommandSpec = CommandSpec {
|
||||
params: r#"{"path": "part.3mf"} — adds each build item of a 3MF package as a surface; triangles keep their B-rep face tags (docs/formats/tagged-mesh.md)"#,
|
||||
form: Some(super::forms::IMPORT_MESH),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[],
|
||||
run: import_mesh,
|
||||
};
|
||||
|
||||
fn open(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let new_model = match p.get("model") {
|
||||
None | Some(Value::Null) => false,
|
||||
Some(v) => match v.as_str() {
|
||||
Some("keep") => false,
|
||||
Some("new") => true,
|
||||
_ => return Err(EngineError::Params(r#"`model` must be "keep" or "new""#.into())),
|
||||
},
|
||||
};
|
||||
let path = super::file_param(s, p, "path", Access::Read)?;
|
||||
let bytes = super::file::read_file(&path, MAX_DESIGN_BYTES as u64)?;
|
||||
let source = SourceFile::of(super::file::absolute(&path), &bytes)?;
|
||||
let design = open_design(&bytes)?;
|
||||
let opened = open_design(&bytes)?;
|
||||
// The model's partitions cut the design again (a new model has none).
|
||||
let design = if new_model { opened } else { super::datum::partitioned(&opened, &s.model)? };
|
||||
let mut fit = fit(s, &design);
|
||||
if new_model {
|
||||
let mut model = Model::default();
|
||||
model.set_units(s.model.units());
|
||||
s.model = model;
|
||||
s.surfaces.clear();
|
||||
s.sources.meshes.clear();
|
||||
s.results_view = None;
|
||||
// A new model is untitled: saving asks for a file instead of overwriting the old model's
|
||||
// (undo brings the old file back with the old model).
|
||||
s.set_document(Default::default());
|
||||
fit.mesh_bodies.clear();
|
||||
fit.sets.clear();
|
||||
fit.seeds.clear();
|
||||
}
|
||||
let out = json!({
|
||||
"name": design.name,
|
||||
"bodies": design.bodies.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(),
|
||||
"errors": design.errors.iter().map(|e| json!({"feature": e.feature, "message": e.message})).collect::<Vec<_>>(),
|
||||
"model": if new_model { "new" } else { "kept" },
|
||||
"related": fit.related,
|
||||
"stale": {"mesh_bodies": fit.mesh_bodies, "sets": fit.sets, "seeds": fit.seeds},
|
||||
});
|
||||
// Another design file (or a new model) is another document; the same file opened again after
|
||||
// an edit is the same one.
|
||||
if new_model || s.sources.design.as_ref().is_none_or(|d| d.path() != source.path()) {
|
||||
s.mark_opened();
|
||||
}
|
||||
s.design = Some(Arc::new(design));
|
||||
s.sources.design = Some(source);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// How the model's geometry references fit a design about to become the geometry.
|
||||
struct Fit {
|
||||
/// Whether the design (or an imported surface) has a body the model refers to, or the model
|
||||
/// refers to none: `false` means the model is of another part.
|
||||
related: bool,
|
||||
/// Bodies the mesh is tagged with that neither the design nor a surface has.
|
||||
mesh_bodies: Vec<String>,
|
||||
/// Sets naming a body or a face that is not there.
|
||||
sets: Vec<String>,
|
||||
/// Edge seeds on an edge the design lacks.
|
||||
seeds: Vec<String>,
|
||||
}
|
||||
|
||||
fn fit(s: &Session, design: &Design) -> Fit {
|
||||
let has = |body: &str| design.body(body).is_some() || s.surfaces.iter().any(|t| t.name == body);
|
||||
let resolves = |r: &GeometryRef| match (&r.entity, design.body(&r.body)) {
|
||||
(Entity::Face(face), Some(b)) => b.faces().iter().any(|f| &f.name == face),
|
||||
_ => has(&r.body),
|
||||
};
|
||||
let tagged: BTreeSet<&str> = s.model.classification().entities().iter().map(|r| r.body.as_str()).collect();
|
||||
let mut referenced = tagged.clone();
|
||||
referenced.extend(s.model.sets().values().flat_map(|set| set.geometry.iter().map(|r| r.body.as_str())));
|
||||
Fit {
|
||||
related: referenced.is_empty() || referenced.iter().any(|b| has(b)),
|
||||
mesh_bodies: tagged.into_iter().filter(|b| !has(b)).map(str::to_string).collect(),
|
||||
sets: s.model.sets().iter().filter(|(_, set)| !set.geometry.iter().all(resolves)).map(|(n, _)| n.clone()).collect(),
|
||||
seeds: s
|
||||
.model
|
||||
.seeds()
|
||||
.iter()
|
||||
.filter(|seed| super::seeds::seeded_edges(design, &seed.edge).map_or(true, |e| e.is_empty()))
|
||||
.map(|seed| seed.edge.to_string())
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn bodies(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let Some(design) = &s.design else { return Ok(json!([])) };
|
||||
let mut out = Vec::with_capacity(design.bodies.len());
|
||||
for b in &design.bodies {
|
||||
let m = b.measure()?;
|
||||
let edges: Vec<Value> = b.edges()?.iter().map(|e| json!({"name": e.name, "length": e.length()})).collect();
|
||||
out.push(json!({
|
||||
"name": b.name,
|
||||
"volume": m.volume,
|
||||
@@ -71,20 +150,21 @@ fn bodies(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
"centroid": m.centroid,
|
||||
"bbox": [m.bbox_min, m.bbox_max],
|
||||
"faces": b.faces().iter().map(|f| json!({"name": f.name, "exact": f.exact})).collect::<Vec<_>>(),
|
||||
"edges": edges,
|
||||
}));
|
||||
}
|
||||
Ok(Value::Array(out))
|
||||
}
|
||||
|
||||
fn body<'a>(s: &'a Session, p: &Value) -> Result<&'a Shape> {
|
||||
let name = p.get("body").and_then(Value::as_str).ok_or_else(|| EngineError::Params("`body` must be a body name".into()))?;
|
||||
let name = p.get("body").and_then(Value::as_str).ok_or_else(|| EngineError::param("body", ProblemKind::NotAName))?;
|
||||
s.design.as_deref().and_then(|d| d.body(name)).ok_or_else(|| EngineError::Params(format!("no body `{name}` (open a design first)")))
|
||||
}
|
||||
|
||||
/// The body named by `body`, tessellated within `tolerance`.
|
||||
pub(crate) fn body_mesh<'a>(s: &'a Session, p: &Value) -> Result<(&'a Shape, SurfaceMesh)> {
|
||||
let shape = body(s, p)?;
|
||||
let tolerance = p.get("tolerance").and_then(Value::as_f64).ok_or_else(|| EngineError::Params("`tolerance` must be a number (mm)".into()))?;
|
||||
let tolerance = p.get("tolerance").and_then(Value::as_f64).ok_or_else(|| EngineError::param("tolerance", ProblemKind::NotANumber))?;
|
||||
Ok((shape, shape.tessellate(tolerance)?))
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Structured hexahedral meshing of the open design's bodies or of imported surfaces.
|
||||
|
||||
use crate::schema::ProblemKind;
|
||||
use std::borrow::Cow;
|
||||
|
||||
use fieldcraft_geometry::{FaceSurface, Shape, SurfaceMesh};
|
||||
@@ -9,14 +10,16 @@ use fieldcraft_mesh::surface::BoundarySurface;
|
||||
use fieldcraft_model::{GeometryRef, Model};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::requirement::Requirement;
|
||||
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
|
||||
|
||||
pub const HEX_GENERATE: CommandSpec = CommandSpec {
|
||||
id: "mesh.hex.generate",
|
||||
label: "Generate Hex Mesh",
|
||||
params: r#"{"body": "Body1" (default: every body of the open design) or "surface": 0 (an imported surface), "size": 2.0 (element size, mm; default 1/25 of the bounding-box diagonal), "order": 1 (hex8) or 2 (hex20, mid-edge nodes on the geometry), "method": "auto" (default) | "swept" (any sweep) | "extrude" | "sweep" | "revolve" | "mapped", "tolerance": 0.05 (chordal tolerance of the tessellation, mm; default 1e-3 of the diagonal)} — replaces the mesh with structured hexahedra: multi-level sweeps along a direction or around an axis, one-to-one sweeps through linking faces, or mapped blocks. Boundary element faces are tagged with their B-rep faces (named as in geometry.bodies; by index when a face has no name; `weld`, `weld_distance` and `feature_angle` as in mesh.tet.generate), so sets by geometry resolve. Reports per body the method, counts and quality; a body no structured method fits is an error that says why"#,
|
||||
label: "Hex Mesh",
|
||||
params: r#"{"body": "Body1" (default: every body of the open design) or "surface": 0 (an imported surface), "size": 2.0 (element size, mm; default 1/25 of the bounding-box diagonal), "order": 1 (hex8) or 2 (hex20, mid-edge nodes on the geometry), "method": "auto" (default) | "swept" (any sweep) | "extrude" | "sweep" | "revolve" | "mapped", "tolerance": 0.05 (chordal tolerance of the tessellation, mm; default 1e-3 of the diagonal)} — replaces the meshes of the bodies it meshes (as mesh.tet.generate; other bodies keep theirs) with structured hexahedra: multi-level sweeps along a direction or around an axis (their cross-section cut into mappable blocks automatically: O-grids round holes, triangle primitives, four-sided blocks; nothing is added to the model), one-to-one sweeps through linking faces, or mapped blocks. Boundary element faces are tagged with their B-rep faces (named as in geometry.bodies; by index when a face has no name; `weld`, `weld_distance` and `feature_angle` as in mesh.tet.generate), so sets by geometry resolve. Edge seeds (mesh.seed.edge) set the counts and spacing of their edges: exact seeds are held, and seeds that cannot all hold (opposite sides of a mapped face, the layers between two levels) are an error naming them. Reports per body the method, counts and quality; a body no structured method fits is an error that says why"#,
|
||||
form: Some(super::forms::HEX_GENERATE),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Geometry],
|
||||
run: hex_generate,
|
||||
};
|
||||
|
||||
@@ -33,9 +36,12 @@ const DEFAULT_RELATIVE_TOLERANCE: f64 = 1e-3;
|
||||
pub(super) struct Input<'a> {
|
||||
pub(super) name: String,
|
||||
pub(super) mesh: Cow<'a, SurfaceMesh>,
|
||||
surfaces: Vec<Option<Surface>>,
|
||||
pub(super) surfaces: Vec<Option<Surface>>,
|
||||
pub(super) face_names: Vec<String>,
|
||||
pub(super) diagonal: f64,
|
||||
/// The design's edge seeds ([`super::seeds::edge_seeds`]); the mesher applies those on its
|
||||
/// edges.
|
||||
pub(super) seeds: Vec<fieldcraft_mesh::seeds::EdgeSeed>,
|
||||
}
|
||||
|
||||
fn analytic(s: FaceSurface) -> Surface {
|
||||
@@ -51,11 +57,7 @@ fn analytic(s: FaceSurface) -> Surface {
|
||||
pub(super) fn number(p: &Value, key: &str) -> Result<Option<f64>> {
|
||||
match p.get(key) {
|
||||
None => Ok(None),
|
||||
Some(v) => v
|
||||
.as_f64()
|
||||
.filter(|x| x.is_finite() && *x > 0.0)
|
||||
.map(Some)
|
||||
.ok_or_else(|| EngineError::Params(format!("`{key}` must be a positive number (mm)"))),
|
||||
Some(v) => v.as_f64().filter(|x| x.is_finite() && *x > 0.0).map(Some).ok_or_else(|| EngineError::param(key, ProblemKind::NotPositive)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,7 +65,7 @@ fn diagonal(lo: [f64; 3], hi: [f64; 3]) -> f64 {
|
||||
(0..3).map(|i| (hi[i] - lo[i]).powi(2)).sum::<f64>().sqrt()
|
||||
}
|
||||
|
||||
fn shape_input(shape: &Shape, tolerance: Option<f64>) -> Result<Input<'static>> {
|
||||
pub(super) fn shape_input(shape: &Shape, tolerance: Option<f64>) -> Result<Input<'static>> {
|
||||
let diag = shape.size()?;
|
||||
let tol = tolerance.unwrap_or(DEFAULT_RELATIVE_TOLERANCE * diag);
|
||||
if tol < MIN_RELATIVE_TOLERANCE * diag {
|
||||
@@ -71,26 +73,33 @@ fn shape_input(shape: &Shape, tolerance: Option<f64>) -> Result<Input<'static>>
|
||||
}
|
||||
let surfaces = shape.face_surfaces()?.into_iter().map(|f| f.map(analytic)).collect();
|
||||
let face_names = shape.faces().iter().map(|f| f.name.clone()).collect();
|
||||
Ok(Input { name: shape.name.clone(), mesh: Cow::Owned(shape.tessellate(tol)?), surfaces, face_names, diagonal: diag })
|
||||
Ok(Input { name: shape.name.clone(), mesh: Cow::Owned(shape.tessellate(tol)?), surfaces, face_names, diagonal: diag, seeds: Vec::new() })
|
||||
}
|
||||
|
||||
/// The imported surface `surface` names, with the body name its mesh is tagged with.
|
||||
pub(super) fn surface<'a>(s: &'a Session, p: &Value) -> Result<(String, &'a fieldcraft_geometry::tagged_mesh::TaggedSurface)> {
|
||||
let n = s.surfaces.len();
|
||||
let index = p.get("surface").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()).filter(|&i| i < n);
|
||||
let index = index.ok_or_else(|| EngineError::Params(format!("`surface` must be the index of an imported surface (there are {n})")))?;
|
||||
let t = s.surfaces.get(index).ok_or_else(|| EngineError::Params("no such surface".into()))?;
|
||||
let name = if t.name.trim().is_empty() { format!("Surface{index}") } else { t.name.clone() };
|
||||
Ok((name, t))
|
||||
}
|
||||
|
||||
pub(super) fn inputs<'a>(s: &'a Session, p: &Value) -> Result<Vec<Input<'a>>> {
|
||||
let tolerance = number(p, "tolerance")?;
|
||||
match (p.get("body"), p.get("surface")) {
|
||||
(Some(b), None) => {
|
||||
let name = b.as_str().ok_or_else(|| EngineError::Params("`body` must be a body name".into()))?;
|
||||
let name = b.as_str().ok_or_else(|| EngineError::param("body", ProblemKind::NotAName))?;
|
||||
let shape = s
|
||||
.design
|
||||
.as_deref()
|
||||
.and_then(|d| d.body(name))
|
||||
.ok_or_else(|| EngineError::Params(format!("no body `{name}` (open a design first)")))?;
|
||||
Ok(vec![shape_input(shape, tolerance)?])
|
||||
Ok(vec![Input { seeds: super::seeds::edge_seeds(s)?, ..shape_input(shape, tolerance)? }])
|
||||
}
|
||||
(None, Some(i)) => {
|
||||
let n = s.surfaces.len();
|
||||
let index = i.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|&i| i < n);
|
||||
let index = index.ok_or_else(|| EngineError::Params(format!("`surface` must be the index of an imported surface (there are {n})")))?;
|
||||
let t = s.surfaces.get(index).ok_or_else(|| EngineError::Params("no such surface".into()))?;
|
||||
(None, Some(_)) => {
|
||||
let (name, t) = surface(s, p)?;
|
||||
let (mut lo, mut hi) = ([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]);
|
||||
for q in &t.mesh.positions {
|
||||
for k in 0..3 {
|
||||
@@ -98,17 +107,17 @@ pub(super) fn inputs<'a>(s: &'a Session, p: &Value) -> Result<Vec<Input<'a>>> {
|
||||
hi[k] = hi[k].max(q[k]);
|
||||
}
|
||||
}
|
||||
let name = if t.name.trim().is_empty() { format!("Surface{index}") } else { t.name.clone() };
|
||||
// Faces named by index, as mesh.tet.generate names them.
|
||||
let face_names = (0..t.faces).map(|f| f.to_string()).collect();
|
||||
Ok(vec![Input { name, mesh: Cow::Borrowed(&t.mesh), surfaces: Vec::new(), face_names, diagonal: diagonal(lo, hi) }])
|
||||
Ok(vec![Input { name, mesh: Cow::Borrowed(&t.mesh), surfaces: Vec::new(), face_names, diagonal: diagonal(lo, hi), seeds: Vec::new() }])
|
||||
}
|
||||
(None, None) => {
|
||||
let design = s.design.as_deref().ok_or_else(|| EngineError::Params("open a design first, or give `surface`".into()))?;
|
||||
if design.bodies.is_empty() || design.bodies.len() > MAX_BODIES {
|
||||
return Err(EngineError::Params(format!("the design has {} bodies; meshing takes 1 to {MAX_BODIES}", design.bodies.len())));
|
||||
}
|
||||
design.bodies.iter().map(|b| shape_input(b, tolerance)).collect()
|
||||
let seeds = super::seeds::edge_seeds(s)?;
|
||||
design.bodies.iter().map(|b| Ok(Input { seeds: seeds.clone(), ..shape_input(b, tolerance)? })).collect()
|
||||
}
|
||||
_ => Err(EngineError::Params("give `body` or `surface`, not both".into())),
|
||||
}
|
||||
@@ -120,6 +129,7 @@ pub const HEX_SWEEP: CommandSpec = CommandSpec {
|
||||
params: r#"the parameters of mesh.hex.generate, with "method": "swept" (default: extrude, sweep or revolve, whichever fits first) | "extrude" | "sweep" | "revolve" — mesh.hex.generate limited to the sweeping methods"#,
|
||||
form: Some(super::forms::HEX_SWEEP),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Geometry],
|
||||
run: hex_sweep,
|
||||
};
|
||||
|
||||
@@ -129,33 +139,35 @@ pub const HEX_MAPPED: CommandSpec = CommandSpec {
|
||||
params: r#"the parameters of mesh.hex.generate without "method" — mesh.hex.generate with the mapped method: a six-sided block (six faces of four edges, three edges at each of eight corners)"#,
|
||||
form: Some(super::forms::HEX_MAPPED),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Geometry],
|
||||
run: hex_mapped,
|
||||
};
|
||||
|
||||
pub const HEX_BLOCKS: CommandSpec = CommandSpec {
|
||||
id: "mesh.hex.blocks",
|
||||
label: "Block Hex Mesh",
|
||||
params: r#"{"bodies": ["Cell1", "Cell2"] (default: every body of the open design), "size": 2.0 (element size, mm; default 1/25 of the bounding-box diagonal of all of them), "order": 1 (hex8) or 2 (hex20, mid-edge nodes on the geometry), "tolerance": 0.05 (chordal tolerance of the tessellation, mm; default 1e-3 of that diagonal)} — replaces the mesh with one conforming all-hex mesh of a part partitioned into cells (bodies that meet face to face, such as the pieces of solid.split_body in SolidCraft): every cell a mapped block (six four-sided faces; faces that meet smoothly, such as the two halves of a hole, count as one), division counts assigned over all cells together, each shared face meshed once and its nodes merged, radial lines graded off holes and fillets. Elements are tagged with their cell's body and boundary faces with its B-rep faces (`weld`, `weld_distance` and `feature_angle` as in mesh.tet.generate). Reports the cells, the shared faces, counts and quality; a cell that is not a block, or cells that touch without sharing whole faces, is an error that says which"#,
|
||||
params: r#"{"bodies": ["Cell1", "Cell2"] (default: every body of the open design), "size": 2.0 (element size, mm; default 1/25 of the bounding-box diagonal of all of them), "order": 1 (hex8) or 2 (hex20, mid-edge nodes on the geometry), "tolerance": 0.05 (chordal tolerance of the tessellation, mm; default 1e-3 of that diagonal)} — replaces the cells' meshes (as mesh.tet.generate; other bodies keep theirs) with one conforming all-hex mesh of a part partitioned into cells (bodies that meet face to face, such as the pieces of solid.split_body in SolidCraft): every cell a mapped block (six four-sided faces; faces that meet smoothly, such as the two halves of a hole, count as one), division counts assigned over all cells together, each shared face meshed once and its nodes merged, radial lines graded off holes and fillets. Elements are tagged with their cell's body and boundary faces with its B-rep faces (`weld`, `weld_distance` and `feature_angle` as in mesh.tet.generate). Reports the cells, the shared faces, counts and quality; a cell that is not a block, or cells that touch without sharing whole faces, is an error that says which"#,
|
||||
form: Some(super::forms::HEX_BLOCKS),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Design],
|
||||
run: hex_blocks,
|
||||
};
|
||||
|
||||
fn hex_blocks(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(super) fn hex_blocks(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let size = number(p, "size")?;
|
||||
let quadratic = order(p)?;
|
||||
let design = s.design.as_deref().ok_or_else(|| EngineError::Params("open a design first".into()))?;
|
||||
let shapes: Vec<&Shape> = match p.get("bodies") {
|
||||
None => design.bodies.iter().collect(),
|
||||
Some(v) => {
|
||||
let names = v.as_array().ok_or_else(|| EngineError::Params("`bodies` must be a list of body names".into()))?;
|
||||
let names = v.as_array().ok_or_else(|| EngineError::param("bodies", ProblemKind::NotNames))?;
|
||||
// Bounded before the duplicate check, which is quadratic in the list.
|
||||
if names.len() > MAX_CELLS {
|
||||
return Err(EngineError::Params(format!("`bodies` lists {} bodies; at most {MAX_CELLS} are meshed together", names.len())));
|
||||
}
|
||||
let mut out: Vec<&Shape> = Vec::with_capacity(names.len());
|
||||
for n in names {
|
||||
let name = n.as_str().ok_or_else(|| EngineError::Params("`bodies` must be a list of body names".into()))?;
|
||||
let name = n.as_str().ok_or_else(|| EngineError::param("bodies", ProblemKind::NotNames))?;
|
||||
let shape = design.body(name).ok_or_else(|| EngineError::Params(format!("no body `{name}`")))?;
|
||||
if out.iter().any(|b| b.name == shape.name) {
|
||||
return Err(EngineError::Params(format!("body `{name}` is listed twice")));
|
||||
@@ -205,14 +217,17 @@ fn hex_blocks(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
quadratic,
|
||||
chordal_tolerance: tolerance,
|
||||
max_elements: fieldcraft_model::MAX_ELEMENTS / 8,
|
||||
seeds: super::seeds::edge_seeds(s)?,
|
||||
..HexOptions::default()
|
||||
};
|
||||
let cm = hex_mesh_cells(&cells, &UniformSize(h), &options).map_err(|e| EngineError::Params(e.to_string()))?;
|
||||
let m = &cm.mesh;
|
||||
// Replace the mesh: definitions stay, nodes, elements and geometry tags are new.
|
||||
let mut model = s.model.without_mesh();
|
||||
// Replace the cells' meshes (replace.rs); other bodies and the definitions stay.
|
||||
let model = &mut s.model;
|
||||
let cleared = super::replace::clear(model, inputs.iter().map(|b| b.name.as_str()));
|
||||
let (first_node, first_element) = super::fresh_labels(model, m.nodes.len(), m.element_count())?;
|
||||
for (i, xyz) in m.nodes.iter().enumerate() {
|
||||
model.set_node(label(i)?, *xyz)?;
|
||||
model.set_node(first_node + i as u32, *xyz)?;
|
||||
}
|
||||
let mut body_tags = Vec::with_capacity(inputs.len());
|
||||
for b in &inputs {
|
||||
@@ -220,15 +235,15 @@ fn hex_blocks(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
for e in 0..m.element_count() {
|
||||
let cell = cm.element_cell.get(e).map_or(0, |&c| c as usize);
|
||||
let nodes: Vec<u32> = m.element(e).unwrap_or(&[]).iter().map(|&i| i + 1).collect();
|
||||
model.set_element(label(e)?, m.kind, nodes)?;
|
||||
model.tag_element(label(e)?, body_tags.get(cell).copied().ok_or_else(|| EngineError::Params("element without a cell".into()))?)?;
|
||||
let nodes: Vec<u32> = m.element(e).unwrap_or(&[]).iter().map(|&i| first_node + i).collect();
|
||||
let l = first_element + e as u32;
|
||||
model.set_element(l, m.kind, nodes)?;
|
||||
model.tag_element(l, body_tags.get(cell).copied().ok_or_else(|| EngineError::Params("element without a cell".into()))?)?;
|
||||
}
|
||||
tag_faces(&mut model, &inputs, |e| cm.element_cell.get(e as usize).map_or(0, |&c| c as usize), &m.boundary, 1)?;
|
||||
s.model = model;
|
||||
tag_faces(model, &inputs, |e| cm.element_cell.get(e as usize).map_or(0, |&c| c as usize), &m.boundary, first_element)?;
|
||||
let blocks: Vec<Value> =
|
||||
inputs.iter().zip(&cm.blocks).map(|(b, d)| json!({"body": b.name, "divisions": d, "elements": d.iter().product::<usize>()})).collect();
|
||||
Ok(json!({
|
||||
let reply = json!({
|
||||
"cells": inputs.len(),
|
||||
"interfaces": cm.interfaces,
|
||||
"description": m.report.description,
|
||||
@@ -241,12 +256,8 @@ fn hex_blocks(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"surface_volume": m.report.surface_volume,
|
||||
"size": h,
|
||||
"blocks": blocks,
|
||||
}))
|
||||
}
|
||||
|
||||
/// A 1-based model label for 0-based index `i`.
|
||||
fn label(i: usize) -> Result<u32> {
|
||||
u32::try_from(i).ok().and_then(|x| x.checked_add(1)).ok_or_else(|| EngineError::Params("too many nodes or elements".into()))
|
||||
});
|
||||
Ok(cleared.report(s, reply))
|
||||
}
|
||||
|
||||
/// The `order` parameter: false for hex8, true for hex20.
|
||||
@@ -256,7 +267,7 @@ fn order(p: &Value) -> Result<bool> {
|
||||
Some(v) => match v.as_u64() {
|
||||
Some(1) => Ok(false),
|
||||
Some(2) => Ok(true),
|
||||
_ => Err(EngineError::Params("`order` must be 1 (hex8) or 2 (hex20)".into())),
|
||||
_ => Err(EngineError::invalid("order", "must be 1 (hex8) or 2 (hex20)")),
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -288,41 +299,16 @@ fn generate(s: &mut Session, p: &Value, default: HexMethod, allowed: &[HexMethod
|
||||
let bodies = inputs(s, p)?;
|
||||
let mut meshes: Vec<(Input, HexMesh)> = Vec::with_capacity(bodies.len());
|
||||
for b in bodies {
|
||||
if !(b.diagonal > 0.0 && b.diagonal.is_finite()) {
|
||||
return Err(EngineError::Params(format!("body `{}` has no extent", b.name)));
|
||||
}
|
||||
let h = size.unwrap_or(DEFAULT_RELATIVE_SIZE * b.diagonal);
|
||||
if h < MIN_RELATIVE_SIZE * b.diagonal {
|
||||
return Err(EngineError::Params(format!("`size` must be at least {} mm for body `{}`", MIN_RELATIVE_SIZE * b.diagonal, b.name)));
|
||||
}
|
||||
let surface_options = super::mesh::surface_options(p, &b.mesh)?;
|
||||
let surface = BoundarySurface::new(&b.mesh.positions, &b.mesh.triangles, &b.mesh.tri_face, &surface_options)
|
||||
.map_err(|e| EngineError::Params(format!("body `{}`: {e}", b.name)))?;
|
||||
let chord = if b.surfaces.is_empty() { 0.0 } else { number(p, "tolerance")?.unwrap_or(DEFAULT_RELATIVE_TOLERANCE * b.diagonal) };
|
||||
let options =
|
||||
HexOptions { method, quadratic, chordal_tolerance: chord, max_elements: fieldcraft_model::MAX_ELEMENTS / 8, ..HexOptions::default() };
|
||||
let mesh = hex_mesh(&surface, &b.surfaces, &UniformSize(h), &options).map_err(|e| EngineError::Params(format!("body `{}`: {e}", b.name)))?;
|
||||
let mesh = hex_body(p, &b, method, quadratic, size)?;
|
||||
meshes.push((b, mesh));
|
||||
}
|
||||
// Replace the mesh: definitions stay, nodes, elements and geometry tags are new.
|
||||
let mut model = s.model.without_mesh();
|
||||
// Replace the bodies' meshes (replace.rs); other bodies and the definitions stay.
|
||||
// A copy: the inputs borrow the session.
|
||||
let mut model = s.model.clone();
|
||||
let cleared = super::replace::clear(&mut model, meshes.iter().map(|(b, _)| b.name.as_str()));
|
||||
let mut report = Vec::with_capacity(meshes.len());
|
||||
let (mut node_label, mut element_label) = (1u32, 1u32);
|
||||
for (b, m) in &meshes {
|
||||
let first_node = node_label;
|
||||
for xyz in &m.nodes {
|
||||
model.set_node(node_label, *xyz)?;
|
||||
node_label = node_label.checked_add(1).ok_or_else(|| EngineError::Params("too many nodes".into()))?;
|
||||
}
|
||||
let body_tag = model.geometry_tag(&GeometryRef::body(b.name.as_str())?)?;
|
||||
let first_element = element_label;
|
||||
for e in 0..m.element_count() {
|
||||
let nodes: Vec<u32> = m.element(e).unwrap_or(&[]).iter().map(|&i| first_node + i).collect();
|
||||
model.set_element(element_label, m.kind, nodes)?;
|
||||
model.tag_element(element_label, body_tag)?;
|
||||
element_label = element_label.checked_add(1).ok_or_else(|| EngineError::Params("too many elements".into()))?;
|
||||
}
|
||||
tag_faces(&mut model, std::slice::from_ref(b), |_| 0, &m.boundary, first_element)?;
|
||||
add_hex(&mut model, b, m)?;
|
||||
report.push(json!({
|
||||
"body": b.name,
|
||||
"method": m.report.method.name(),
|
||||
@@ -336,8 +322,53 @@ fn generate(s: &mut Session, p: &Value, default: HexMethod, allowed: &[HexMethod
|
||||
"surface_volume": m.report.surface_volume,
|
||||
}));
|
||||
}
|
||||
let (nodes, elements) = (model.nodes().len(), model.elements().len());
|
||||
s.model = model;
|
||||
Ok(json!({"bodies": report, "nodes": node_label - 1, "elements": element_label - 1}))
|
||||
Ok(cleared.report(s, json!({"bodies": report, "nodes": nodes, "elements": elements})))
|
||||
}
|
||||
|
||||
/// Mesh one body with `method` (hex20 when `quadratic`) at `size` (default: from its extent);
|
||||
/// the model is not touched. Errors name the body.
|
||||
pub(super) fn hex_body(p: &Value, b: &Input, method: HexMethod, quadratic: bool, size: Option<f64>) -> Result<HexMesh> {
|
||||
if !(b.diagonal > 0.0 && b.diagonal.is_finite()) {
|
||||
return Err(EngineError::Params(format!("body `{}` has no extent", b.name)));
|
||||
}
|
||||
let h = size.unwrap_or(DEFAULT_RELATIVE_SIZE * b.diagonal);
|
||||
if h < MIN_RELATIVE_SIZE * b.diagonal {
|
||||
return Err(EngineError::Params(format!("`size` must be at least {} mm for body `{}`", MIN_RELATIVE_SIZE * b.diagonal, b.name)));
|
||||
}
|
||||
let surface_options = super::mesh::surface_options(p, &b.mesh)?;
|
||||
let surface = BoundarySurface::new(&b.mesh.positions, &b.mesh.triangles, &b.mesh.tri_face, &surface_options)
|
||||
.map_err(|e| EngineError::Params(format!("body `{}`: {e}", b.name)))?;
|
||||
let chord = if b.surfaces.is_empty() { 0.0 } else { number(p, "tolerance")?.unwrap_or(DEFAULT_RELATIVE_TOLERANCE * b.diagonal) };
|
||||
let options = HexOptions {
|
||||
method,
|
||||
quadratic,
|
||||
chordal_tolerance: chord,
|
||||
max_elements: fieldcraft_model::MAX_ELEMENTS / 8,
|
||||
seeds: b.seeds.clone(),
|
||||
..HexOptions::default()
|
||||
};
|
||||
hex_mesh(&surface, &b.surfaces, &UniformSize(h), &options).map_err(|e| EngineError::Params(format!("body `{}`: {e}", b.name)))
|
||||
}
|
||||
|
||||
/// Add one body's hex mesh after the model's largest labels, tagging the elements with the body
|
||||
/// and the boundary element faces with its B-rep faces; returns the first node and element
|
||||
/// labels.
|
||||
pub(super) fn add_hex(model: &mut Model, b: &Input, m: &HexMesh) -> Result<(u32, u32)> {
|
||||
let (first_node, first_element) = super::fresh_labels(model, m.nodes.len(), m.element_count())?;
|
||||
for (i, xyz) in m.nodes.iter().enumerate() {
|
||||
model.set_node(first_node + i as u32, *xyz)?;
|
||||
}
|
||||
let body_tag = model.geometry_tag(&GeometryRef::body(b.name.as_str())?)?;
|
||||
for e in 0..m.element_count() {
|
||||
let nodes: Vec<u32> = m.element(e).unwrap_or(&[]).iter().map(|&i| first_node + i).collect();
|
||||
let l = first_element + e as u32;
|
||||
model.set_element(l, m.kind, nodes)?;
|
||||
model.tag_element(l, body_tag)?;
|
||||
}
|
||||
tag_faces(model, std::slice::from_ref(b), |_| 0, &m.boundary, first_element)?;
|
||||
Ok((first_node, first_element))
|
||||
}
|
||||
|
||||
/// Tag every boundary element face with the B-rep face it lies on, of the body
|
||||
@@ -471,6 +502,22 @@ mod tests {
|
||||
assert_eq!(two["cells"], 2);
|
||||
}
|
||||
|
||||
/// The Partitioned Mesh form's "All hex" option is mesh.hex.blocks.
|
||||
#[test]
|
||||
fn mesh_cells_all_blocks_is_mesh_hex_blocks() {
|
||||
let (_dir, mut s) = split_box(false);
|
||||
let blocks = s.execute("mesh.hex.blocks", &json!({"size": 2.5})).unwrap();
|
||||
let mut cells = s.execute("mesh.cells", &json!({"default": "blocks", "size": 2.5})).unwrap();
|
||||
let mut blocks = blocks;
|
||||
// The same mesh, in place of the first one.
|
||||
let replaced = cells.as_object_mut().and_then(|o| o.remove("replaced")).unwrap();
|
||||
assert_eq!(replaced.as_array().map(Vec::len), Some(4), "{replaced}");
|
||||
blocks.as_object_mut().and_then(|o| o.remove("replaced"));
|
||||
assert_eq!(cells, blocks);
|
||||
let e = s.execute("mesh.cells", &json!({"default": "blocks", "methods": {"Box": "tet"}})).unwrap_err().to_string();
|
||||
assert!(e.contains("methods"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cells_that_do_not_conform_and_hostile_params_are_errors() {
|
||||
let (_dir, mut s) = split_box(true);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use crate::schema::ProblemKind;
|
||||
use std::borrow::Cow;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
@@ -13,6 +14,7 @@ use fieldcraft_model::{ElementKind, GeometryRef, MAX_ELEMENTS};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{label, labels, listed, optional_number, points, xyz};
|
||||
use crate::requirement::Requirement;
|
||||
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
|
||||
|
||||
pub const NODE_ADD: CommandSpec = CommandSpec {
|
||||
@@ -21,6 +23,7 @@ pub const NODE_ADD: CommandSpec = CommandSpec {
|
||||
params: r#"{"label": 1, "xyz": [x, y, z]} — adds the node, or moves it if the label exists"#,
|
||||
form: Some(super::forms::NODE_ADD),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[],
|
||||
run: node_add,
|
||||
};
|
||||
|
||||
@@ -30,6 +33,7 @@ pub const NODE_REMOVE: CommandSpec = CommandSpec {
|
||||
params: r#"{"label": 1} — only a node no element uses"#,
|
||||
form: Some(super::forms::LABEL),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Nodes],
|
||||
run: node_remove,
|
||||
};
|
||||
|
||||
@@ -39,6 +43,7 @@ pub const ELEMENT_ADD: CommandSpec = CommandSpec {
|
||||
params: r#"{"label": 1, "kind": "rod2|beam2|tri3|tri6|quad4|quad8|tet4|tet10|wedge6|hex8|hex20", "nodes": [labels]} — adds or replaces"#,
|
||||
form: Some(super::forms::ELEMENT_ADD),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Nodes],
|
||||
run: element_add,
|
||||
};
|
||||
|
||||
@@ -48,6 +53,7 @@ pub const ELEMENT_REMOVE: CommandSpec = CommandSpec {
|
||||
params: r#"{"label": 1}"#,
|
||||
form: Some(super::forms::LABEL),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Mesh],
|
||||
run: element_remove,
|
||||
};
|
||||
|
||||
@@ -57,6 +63,7 @@ pub const QUALITY: CommandSpec = CommandSpec {
|
||||
params: r#"{"elements": [labels] (optional, default all), "bins": 10 (1..=1000)} — certified validity (det J > 0 everywhere), volume, and min/max/mean/worst/histogram per metric (angles in degrees; histograms over each metric's fixed range, out-of-range values in the end bins)"#,
|
||||
form: Some(super::forms::QUALITY),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Mesh],
|
||||
run: quality_report,
|
||||
};
|
||||
|
||||
@@ -66,6 +73,7 @@ pub const DELAUNAY_POINTS: CommandSpec = CommandSpec {
|
||||
params: r#"{"points": [[x, y, z], ...] (at most 20000)} — the exact Delaunay tetrahedralization (a debugging report; the model is not changed): {"dimension", "vertices", "duplicates": [[point, kept point], ...], "tets": [[i, j, k, l], ...]} with 0-based point indices in tet4 order; collinear or coplanar points give no tets"#,
|
||||
form: Some(super::forms::DELAUNAY_POINTS),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[],
|
||||
run: delaunay_points,
|
||||
};
|
||||
|
||||
@@ -92,15 +100,17 @@ pub const SURFACE_CHECK: CommandSpec = CommandSpec {
|
||||
params: r#"{"body": "Body1", "tolerance": 0.05} or {"surface": 0}, optional "weld": 1e-9 (0 or 1e-15..=1e-3 of the bounding-box diagonal), "weld_distance": mm (default: the surface's own, twice SolidCraft's linear tolerance for a tessellated body, 0 for an imported mesh), "feature_angle": 45 (degrees, (0, 180]) — welds the tessellated body or imported surface and checks it can bound a volume mesh: closed, manifold, outward, no self-intersections; reports shells, genus, volume and feature edges, or the located defects"#,
|
||||
form: Some(super::forms::SURFACE_CHECK),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Geometry],
|
||||
run: surface_check,
|
||||
};
|
||||
|
||||
pub const TET_GENERATE: CommandSpec = CommandSpec {
|
||||
id: "mesh.tet.generate",
|
||||
label: "Generate Tet Mesh",
|
||||
params: r#"{"body": "Body1" (default: every body of the open design) or "surface": 0 (an imported surface), "tolerance": 0.05 (chordal tolerance of the tessellation, mm; default 1e-3 of the body's bounding-box diagonal), the boundary options of mesh.surface.check ("weld", "weld_distance", "feature_angle"), optional "size": mm (target edge length; default a twentieth of the bounding-box diagonal), "order": "linear" | "quadratic" (tet4 or tet10; quadratic mid-edge nodes lie on the B-rep faces), "quality": true (false: the raw constrained Delaunay tetrahedralization), "quality_target": 40 (degrees: tetrahedra whose smallest dihedral-angle sine is at least sin of this are left alone by improvement, 5..=60), "curvature_angle": 22.5 (degrees per element along curved boundary, 0 for none, at most 90), "grading": 0.3 (largest size change per unit length, 0.05..=2), "max_passes": 20 (improvement passes, 0..=200), "max_points": 1000000 (1..=20000000), "max_steiner": 50000 (0..=10000000), "max_tets": 5000000 (1..=50000000) — the constrained Delaunay tetrahedralization of the welded boundary (every boundary triangle a union of tet faces), refined to the size field with its boundary vertices on the B-rep faces, smoothed and improved (Delaunay refinement, ODT smoothing, Klingner–Shewchuk improvement), with a quality report. Adds the elements and their nodes (labels after the largest existing ones), tags the elements with the body and each boundary element face with its geometry face, and fails, changing nothing, if a surface is invalid or a mesh does not pass the validity gate. Reports the totals and, under `bodies`, each body's counts, size and quality report"#,
|
||||
params: r#"{"body": "Body1" (default: every body of the open design) or "surface": 0 (an imported surface), "tolerance": 0.05 (chordal tolerance of the tessellation, mm; default 1e-3 of the body's bounding-box diagonal), the boundary options of mesh.surface.check ("weld", "weld_distance", "feature_angle"), optional "size": mm (target edge length; default a twentieth of the bounding-box diagonal), "order": "linear" | "quadratic" (tet4 or tet10; quadratic mid-edge nodes lie on the B-rep faces), "quality": true (false: the raw constrained Delaunay tetrahedralization), "quality_target": 40 (degrees: tetrahedra whose smallest dihedral-angle sine is at least sin of this are left alone by improvement, 5..=60), "curvature_angle": 22.5 (degrees per element along curved boundary, 0 for none, at most 90), "grading": 0.3 (largest size change per unit length, 0.05..=2), "max_passes": 20 (improvement passes, 0..=200), "max_points": 1000000 (1..=20000000), "max_steiner": 50000 (0..=10000000), "max_tets": 5000000 (1..=50000000) — the constrained Delaunay tetrahedralization of the welded boundary (every boundary triangle a union of tet faces), refined to the size field with its boundary vertices on the B-rep faces, smoothed and improved (Delaunay refinement, ODT smoothing, Klingner–Shewchuk improvement), with a quality report. Replaces the mesh of each body it meshes (its elements and the nodes only they use; other bodies' meshes stay; the reply's `replaced`, `stale_sets` and `results_cleared` say what went), adds the elements and their nodes (labels after the largest existing ones), tags the elements with the body and each boundary element face with its geometry face, and fails, changing nothing, if a surface is invalid or a mesh does not pass the validity gate. Edge seeds (mesh.seed.edge) divide their edges at the seeded nodes, and the size field grades from them. Reports the totals and, under `bodies`, each body's counts, size, quality report and `seeds` (per seeded edge, the mesh edges along it)"#,
|
||||
form: Some(super::forms::TET),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Geometry],
|
||||
run: tet_generate,
|
||||
};
|
||||
|
||||
@@ -114,12 +124,15 @@ const TET_MAX_PASSES: u64 = 200;
|
||||
pub(super) fn optional_count(p: &Value, key: &str, default: u64, range: std::ops::RangeInclusive<u64>) -> Result<usize> {
|
||||
let v = match p.get(key) {
|
||||
None => default,
|
||||
Some(v) => v
|
||||
.as_u64()
|
||||
.filter(|n| range.contains(n))
|
||||
.ok_or_else(|| EngineError::Params(format!("`{key}` must be a whole number in {}..={}", range.start(), range.end())))?,
|
||||
Some(v) => v.as_u64().filter(|n| range.contains(n)).ok_or_else(|| EngineError::param(key, whole_in(&range)))?,
|
||||
};
|
||||
usize::try_from(v).map_err(|_| EngineError::Params(format!("`{key}` is too large")))
|
||||
usize::try_from(v).map_err(|_| EngineError::param(key, whole_in(&range)))
|
||||
}
|
||||
|
||||
/// A whole number in `range`, as a problem's kind.
|
||||
fn whole_in(range: &std::ops::RangeInclusive<u64>) -> ProblemKind {
|
||||
let int = |n: u64| i64::try_from(n).unwrap_or(i64::MAX);
|
||||
ProblemKind::NotAWholeNumber { min: int(*range.start()), max: int(*range.end()) }
|
||||
}
|
||||
|
||||
/// The boundary options of `mesh.surface.check`, `mesh.tet.generate` and the hex meshers.
|
||||
@@ -135,18 +148,18 @@ pub(super) fn surface_options(p: &Value, mesh: &SurfaceMesh) -> Result<SurfaceOp
|
||||
/// An optional number in `range`.
|
||||
fn number_in(p: &Value, key: &str, default: f64, range: std::ops::RangeInclusive<f64>) -> Result<f64> {
|
||||
let v = optional_number(p, key, default)?;
|
||||
if range.contains(&v) { Ok(v) } else { Err(EngineError::Params(format!("`{key}` must be a number in {}..={}", range.start(), range.end()))) }
|
||||
if range.contains(&v) { Ok(v) } else { Err(EngineError::param(key, ProblemKind::NotInRange { min: *range.start(), max: *range.end() })) }
|
||||
}
|
||||
|
||||
/// The quality options of `mesh.tet.generate`, and whether the quality stage runs at all.
|
||||
fn quality_options(p: &Value, max_tets: u64) -> Result<(QualityOptions, bool)> {
|
||||
pub(super) fn quality_options(p: &Value, max_tets: u64) -> Result<(QualityOptions, bool)> {
|
||||
let d = QualityOptions::default();
|
||||
let size = match p.get("size") {
|
||||
None => None,
|
||||
Some(v) => Some(
|
||||
v.as_f64()
|
||||
.filter(|h| *h > 0.0 && h.is_finite() && *h <= fieldcraft_model::MAX_COORD)
|
||||
.ok_or_else(|| EngineError::Params("`size` must be a positive number (mm)".into()))?,
|
||||
.ok_or_else(|| EngineError::param("size", ProblemKind::NotPositive))?,
|
||||
),
|
||||
};
|
||||
let order = match p.get("order") {
|
||||
@@ -154,7 +167,7 @@ fn quality_options(p: &Value, max_tets: u64) -> Result<(QualityOptions, bool)> {
|
||||
Some(v) => match v.as_str() {
|
||||
Some("linear") => Order::Linear,
|
||||
Some("quadratic") => Order::Quadratic,
|
||||
_ => return Err(EngineError::Params("`order` must be \"linear\" or \"quadratic\"".into())),
|
||||
_ => return Err(EngineError::param("order", ProblemKind::NotAChoice)),
|
||||
},
|
||||
};
|
||||
let target = number_in(p, "quality_target", 40.0, 5.0..=60.0)?;
|
||||
@@ -200,7 +213,7 @@ pub fn analytic_surfaces(shape: &fieldcraft_geometry::Shape) -> Vec<Option<Analy
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn quality_json(q: &TetQuality) -> Value {
|
||||
pub(super) fn quality_json(q: &TetQuality) -> Value {
|
||||
json!({
|
||||
"tets": q.tets,
|
||||
"min_dihedral": q.min_dihedral,
|
||||
@@ -213,10 +226,10 @@ fn quality_json(q: &TetQuality) -> Value {
|
||||
}
|
||||
|
||||
/// One body's tetrahedra, ready to add, with what its report needs of the surface and the CDT.
|
||||
struct BodyTets {
|
||||
name: String,
|
||||
face_names: Vec<String>,
|
||||
mesh: QualityMesh,
|
||||
pub(super) struct BodyTets {
|
||||
pub(super) name: String,
|
||||
pub(super) face_names: Vec<String>,
|
||||
pub(super) mesh: QualityMesh,
|
||||
steiner: usize,
|
||||
cavities: usize,
|
||||
surface_volume: f64,
|
||||
@@ -224,7 +237,7 @@ struct BodyTets {
|
||||
|
||||
/// Mesh one body or imported surface; the model is not touched. With `several` bodies an error
|
||||
/// names the body.
|
||||
fn mesh_body(
|
||||
pub(super) fn mesh_body(
|
||||
s: &Session,
|
||||
p: &Value,
|
||||
input: super::hex::Input,
|
||||
@@ -241,7 +254,12 @@ fn mesh_body(
|
||||
};
|
||||
let surface = BoundarySurface::new(&input.mesh.positions, &input.mesh.triangles, &input.mesh.tri_face, &surface_options(p, &input.mesh)?)?;
|
||||
let tets = tetrahedralize(&surface, cdt)?;
|
||||
let mesh = if quality { quality_mesh(&surface, &tets, analytic, options)? } else { raw_mesh(&surface, &tets)? };
|
||||
let mesh = if quality {
|
||||
let options = QualityOptions { seeds: input.seeds.clone(), ..options.clone() };
|
||||
quality_mesh(&surface, &tets, analytic, &options)?
|
||||
} else {
|
||||
raw_mesh(&surface, &tets)?
|
||||
};
|
||||
Ok(BodyTets {
|
||||
name: input.name.clone(),
|
||||
face_names: input.face_names.clone(),
|
||||
@@ -266,9 +284,11 @@ fn tet_generate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
meshed.push(mesh_body(s, p, input, &cdt_options, &options, quality, several)?);
|
||||
}
|
||||
|
||||
// Replace the bodies' meshes (replace.rs); other bodies and the definitions stay.
|
||||
let cleared = super::replace::clear(&mut s.model, meshed.iter().map(|b| b.name.as_str()));
|
||||
let mut bodies = Vec::with_capacity(meshed.len());
|
||||
for b in &meshed {
|
||||
let (first_node, first_element) = add_tets(s, &b.name, &b.face_names, &b.mesh)?;
|
||||
let (first_node, first_element) = add_tets(&mut s.model, &b.name, &b.face_names, &b.mesh)?;
|
||||
let r = &b.mesh.report;
|
||||
bodies.push(json!({
|
||||
"body": b.name,
|
||||
@@ -292,12 +312,13 @@ fn tet_generate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"straightened": r.straightened,
|
||||
"stopped": r.stopped,
|
||||
},
|
||||
"seeds": r.seeds.iter().map(|(name, count, edges)| json!({"edge": name, "count": count, "mesh_edges": edges})).collect::<Vec<_>>(),
|
||||
}));
|
||||
}
|
||||
let sum = |f: fn(&BodyTets) -> f64| meshed.iter().map(f).sum::<f64>();
|
||||
let count = |f: fn(&BodyTets) -> usize| meshed.iter().map(f).sum::<usize>();
|
||||
let first = bodies.first();
|
||||
Ok(json!({
|
||||
let reply = json!({
|
||||
"kind": meshed.first().map(|b| b.mesh.kind.name()),
|
||||
"nodes": count(|b| b.mesh.points.len()),
|
||||
"elements": count(|b| b.mesh.elements.len()),
|
||||
@@ -308,21 +329,22 @@ fn tet_generate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"boundary_volume": sum(|b| b.mesh.report.boundary_volume),
|
||||
"surface_volume": sum(|b| b.surface_volume),
|
||||
"bodies": bodies,
|
||||
}))
|
||||
});
|
||||
Ok(cleared.report(s, reply))
|
||||
}
|
||||
|
||||
/// Add one body's elements after the model's largest labels, tagging them with the body and each
|
||||
/// boundary element face with its geometry face; returns the first node and element labels.
|
||||
fn add_tets(s: &mut Session, body: &str, face_names: &[String], mesh: &QualityMesh) -> Result<(u32, u32)> {
|
||||
let (first_node, first_element) = super::fresh_labels(&s.model, mesh.points.len(), mesh.elements.len())?;
|
||||
pub(super) fn add_tets(model: &mut fieldcraft_model::Model, body: &str, face_names: &[String], mesh: &QualityMesh) -> Result<(u32, u32)> {
|
||||
let (first_node, first_element) = super::fresh_labels(model, mesh.points.len(), mesh.elements.len())?;
|
||||
for (i, xyz) in mesh.points.iter().enumerate() {
|
||||
s.model.set_node(first_node + i as u32, *xyz)?;
|
||||
model.set_node(first_node + i as u32, *xyz)?;
|
||||
}
|
||||
let body_tag = s.model.geometry_tag(&GeometryRef::body(body)?)?;
|
||||
let body_tag = model.geometry_tag(&GeometryRef::body(body)?)?;
|
||||
for (i, e) in mesh.elements.iter().enumerate() {
|
||||
let label = first_element + i as u32;
|
||||
s.model.set_element(label, mesh.kind, e.iter().map(|&v| first_node + v).collect())?;
|
||||
s.model.tag_element(label, body_tag)?;
|
||||
model.set_element(label, mesh.kind, e.iter().map(|&v| first_node + v).collect())?;
|
||||
model.tag_element(label, body_tag)?;
|
||||
}
|
||||
let mut face_tags: Vec<Option<u32>> = vec![None; face_names.len()];
|
||||
for b in &mesh.boundary {
|
||||
@@ -331,7 +353,7 @@ fn add_tets(s: &mut Session, body: &str, face_names: &[String], mesh: &QualityMe
|
||||
Some(t) => t,
|
||||
None => {
|
||||
let name = face_names.get(face).ok_or_else(|| EngineError::Params(format!("boundary face {} has no geometry face", b.face)))?;
|
||||
let t = s.model.geometry_tag(&GeometryRef::face(body, name.clone())?)?;
|
||||
let t = model.geometry_tag(&GeometryRef::face(body, name.clone())?)?;
|
||||
if let Some(slot) = face_tags.get_mut(face) {
|
||||
*slot = Some(t);
|
||||
}
|
||||
@@ -339,7 +361,7 @@ fn add_tets(s: &mut Session, body: &str, face_names: &[String], mesh: &QualityMe
|
||||
}
|
||||
};
|
||||
let number = b.element_face().ok_or_else(|| EngineError::Params(format!("boundary face {} has no element face number", b.opposite)))?;
|
||||
s.model.tag_element_face(first_element + b.tet, number, tag)?;
|
||||
model.tag_element_face(first_element + b.tet, number, tag)?;
|
||||
}
|
||||
Ok((first_node, first_element))
|
||||
}
|
||||
@@ -347,9 +369,10 @@ fn add_tets(s: &mut Session, body: &str, face_names: &[String], mesh: &QualityMe
|
||||
pub const PLANAR: CommandSpec = CommandSpec {
|
||||
id: "mesh.planar",
|
||||
label: "2D Mesh",
|
||||
params: r#"{"size": 1.0, "kind": "quad4|quad8|tri3|tri6" (default quad4), and either "polygon": [[x, y], ...] with optional "holes": [[[x, y], ...], ...] and "name": "Plane" (the body name its tags use), or "body": "Body1", "face": "F2:top", "tolerance": 0.05 (a planar face of an open design, parallel to XY); optional "max_elements": 1000000 (1..=4000000)} — meshes the planar region with 2D elements in the XY plane (a face at z = c is meshed at z = 0) for plane stress, plane strain or axisymmetric sections (x the radius, Y the axis): free quadrilaterals (or constrained Delaunay triangles) of about `size`, mid-side nodes on the boundary for quadratic kinds. Adds nodes and elements after the largest existing labels and tags them: the elements with the face (polygon: face `area` of body `name`), the boundary element edges with edges named after the neighbouring face of the body (polygon: `e1`, `e2`, … side by side, the outer loop then each hole, and vertices `v1`, … at the corners), so sets on those edges carry loads and boundary conditions"#,
|
||||
params: r#"{"size": 1.0, "kind": "quad4|quad8|tri3|tri6" (default quad4), and either "polygon": [[x, y], ...] with optional "holes": [[[x, y], ...], ...] and "name": "Plane" (the body name its tags use), or "body": "Body1", "face": "F2:top", "tolerance": 0.05 (a planar face of an open design, parallel to XY); optional "max_elements": 1000000 (1..=4000000)} — meshes the planar region with 2D elements in the XY plane (a face at z = c is meshed at z = 0) for plane stress, plane strain or axisymmetric sections (x the radius, Y the axis): free quadrilaterals (or constrained Delaunay triangles) of about `size`, mid-side nodes on the boundary for quadratic kinds. Replaces the body's mesh (as mesh.tet.generate), then adds nodes and elements after the largest existing labels and tags them: the elements with the face (polygon: face `area` of body `name`), the boundary element edges with edges named after the neighbouring face of the body (polygon: `e1`, `e2`, … side by side, the outer loop then each hole, and vertices `v1`, … at the corners), so sets on those edges carry loads and boundary conditions"#,
|
||||
form: Some(super::forms::PLANAR),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[],
|
||||
run: planar,
|
||||
};
|
||||
|
||||
@@ -379,14 +402,14 @@ fn planar(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.get("size")
|
||||
.and_then(Value::as_f64)
|
||||
.filter(|v| *v > 0.0 && v.is_finite())
|
||||
.ok_or_else(|| EngineError::Params("`size` must be a positive number (the element size)".into()))?;
|
||||
.ok_or_else(|| super::wrong(p, "size", ProblemKind::NotPositive))?;
|
||||
let kind = match p.get("kind") {
|
||||
None => ElementKind::Quad4,
|
||||
Some(k) => k
|
||||
.as_str()
|
||||
.and_then(ElementKind::from_name)
|
||||
.filter(|k| k.dimension() == 2)
|
||||
.ok_or_else(|| EngineError::Params("`kind` must be quad4, quad8, tri3 or tri6".into()))?,
|
||||
.ok_or_else(|| EngineError::param("kind", ProblemKind::NotAChoice))?,
|
||||
};
|
||||
let opts = fieldcraft_mesh::quad::QuadOptions {
|
||||
max_elements: optional_count(p, "max_elements", 1_000_000, 1..=PLANAR_MAX_ELEMENTS)?,
|
||||
@@ -408,7 +431,7 @@ fn planar(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let name = match p.get("name") {
|
||||
None => "Plane".to_string(),
|
||||
Some(n) => n.as_str().map(str::to_string).ok_or_else(|| EngineError::Params("`name` must be a body name".into()))?,
|
||||
Some(n) => n.as_str().map(str::to_string).ok_or_else(|| EngineError::param("name", ProblemKind::NotAName))?,
|
||||
};
|
||||
GeometryRef::body(name.clone())?;
|
||||
let mut id = 0u32;
|
||||
@@ -428,7 +451,7 @@ fn planar(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
(loops, name, "area".to_string(), names)
|
||||
}
|
||||
(None, Some(_)) => {
|
||||
let face_name = p.get("face").and_then(Value::as_str).ok_or_else(|| EngineError::Params("`face` must be a face name".into()))?;
|
||||
let face_name = p.get("face").and_then(Value::as_str).ok_or_else(|| EngineError::param("face", ProblemKind::NotAName))?;
|
||||
let (shape, mesh) = super::geometry::body_mesh(s, p)?;
|
||||
let face = shape.face_index(face_name).ok_or_else(|| EngineError::Params(format!("body `{}` has no face `{face_name}`", shape.name)))?;
|
||||
let b = face_boundary(&mesh.positions, &mesh.triangles, &mesh.tri_face, face, mesh.weld_distance)?;
|
||||
@@ -439,6 +462,8 @@ fn planar(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let m = mesh_region(&loops, kind, size, &opts)?;
|
||||
|
||||
// Replace the body's mesh (replace.rs); other bodies and the definitions stay.
|
||||
let cleared = super::replace::clear(&mut s.model, [body.as_str()]);
|
||||
let (first_node, first_element) = super::fresh_labels(&s.model, m.nodes.len(), m.elements.len())?;
|
||||
for (i, xy) in m.nodes.iter().enumerate() {
|
||||
s.model.set_node(first_node + i as u32, [xy[0], xy[1], 0.0])?;
|
||||
@@ -469,8 +494,8 @@ fn planar(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.model.tag_node(first_node + node, t)?;
|
||||
}
|
||||
}
|
||||
let edges: Vec<&String> = tags.keys().filter_map(|id| names.get(id)).collect();
|
||||
Ok(json!({
|
||||
let edges: Vec<String> = tags.keys().filter_map(|id| names.get(id)).cloned().collect();
|
||||
let reply = json!({
|
||||
"body": body,
|
||||
"face": face,
|
||||
"kind": kind.name(),
|
||||
@@ -479,7 +504,18 @@ fn planar(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"first_node": first_node,
|
||||
"first_element": first_element,
|
||||
"edges": edges,
|
||||
}))
|
||||
});
|
||||
Ok(cleared.report(s, reply))
|
||||
}
|
||||
|
||||
/// The body `mesh.planar` fills: `body`, or the polygon's `name` (default `Plane`).
|
||||
pub(super) fn planar_body(_: &Session, p: &Value) -> Result<Vec<String>> {
|
||||
let name = match (p.get("polygon"), p.get("body")) {
|
||||
(Some(_), None) => p.get("name").map_or(Some("Plane"), Value::as_str),
|
||||
(None, Some(b)) => b.as_str(),
|
||||
_ => None,
|
||||
};
|
||||
Ok(vec![name.ok_or_else(|| EngineError::Params("give either `polygon` or `body`".into()))?.to_string()])
|
||||
}
|
||||
|
||||
fn node_add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -518,7 +554,7 @@ fn number(v: f64) -> Value {
|
||||
fn quality_report(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let bins = match p.get("bins") {
|
||||
None => 10,
|
||||
Some(v) => v.as_u64().and_then(|b| usize::try_from(b).ok()).ok_or_else(|| EngineError::Params("`bins` must be a whole number".into()))?,
|
||||
Some(v) => v.as_u64().and_then(|b| usize::try_from(b).ok()).ok_or_else(|| EngineError::invalid("bins", "must be a whole number"))?,
|
||||
};
|
||||
let selection = match p.get("elements") {
|
||||
None => None,
|
||||
@@ -745,8 +781,9 @@ mod tests {
|
||||
// A tagged tetrahedron, and the same with a face missing.
|
||||
let p = vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
|
||||
let t = vec![[0, 2, 1], [0, 1, 3], [1, 2, 3], [0, 3, 2]];
|
||||
let tet = SurfaceMesh { positions: p.clone(), triangles: t.clone(), tri_face: vec![0, 1, 1, 1], weld_distance: 0.0 };
|
||||
let open = SurfaceMesh { positions: p, triangles: t[..3].to_vec(), tri_face: vec![0, 1, 1], weld_distance: 0.0 };
|
||||
let tet =
|
||||
SurfaceMesh { positions: p.clone(), triangles: t.clone(), tri_face: vec![0, 1, 1, 1], weld_distance: 0.0, ..SurfaceMesh::default() };
|
||||
let open = SurfaceMesh { positions: p, triangles: t[..3].to_vec(), tri_face: vec![0, 1, 1], weld_distance: 0.0, ..SurfaceMesh::default() };
|
||||
for mesh in [tet, open] {
|
||||
s.surfaces.push(Arc::new(TaggedSurface { name: "Tet".into(), mesh, faces: 2 }));
|
||||
}
|
||||
@@ -776,7 +813,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tet_generate_meshes_a_body_with_tags_and_appends() {
|
||||
fn tet_generate_meshes_a_body_with_tags_and_replaces_its_mesh() {
|
||||
use std::sync::Arc;
|
||||
|
||||
use fieldcraft_geometry::open_design;
|
||||
@@ -802,11 +839,12 @@ mod tests {
|
||||
let q = s.execute("mesh.quality", &json!({})).unwrap();
|
||||
assert_eq!(q["valid"].as_u64().unwrap() as usize, elements);
|
||||
assert!(q["summary"].as_str().unwrap().starts_with(&format!("{elements} elements, all valid; scaled Jacobian min ")), "{q}");
|
||||
// A second run appends after the existing labels.
|
||||
// A second run replaces the body's mesh (#267).
|
||||
let again = s.execute("mesh.tet.generate", &json!({"body": "Body1", "tolerance": 0.5})).unwrap();
|
||||
assert_eq!(again["first_element"].as_u64().unwrap() as usize, elements + 1);
|
||||
assert_eq!(s.model.elements().len(), 2 * elements);
|
||||
assert_eq!(s.journal.len(), 2);
|
||||
assert_eq!(again["replaced"][0]["elements"].as_u64().unwrap() as usize, elements, "{again}");
|
||||
assert_eq!(s.model.elements().len(), elements);
|
||||
// The same mesh again, under the same labels: nothing changed, so no undo step.
|
||||
assert_eq!(s.journal.len(), 1);
|
||||
|
||||
let journal = s.journal.len();
|
||||
let model = s.model.clone();
|
||||
@@ -837,7 +875,7 @@ mod tests {
|
||||
let bytes = fieldcraft_geometry::script_design(&commands.to_string()).unwrap();
|
||||
let (_dir, path) = crate::tests::design_file(&bytes);
|
||||
let mut s = Session::default();
|
||||
assert!(s.execute("mesh.tet.generate", &json!({})).unwrap_err().to_string().contains("open a design first"));
|
||||
assert!(s.execute("mesh.tet.generate", &json!({})).unwrap_err().to_string().contains("Needs geometry"));
|
||||
s.execute("geometry.open", &json!({"path": path})).unwrap();
|
||||
let r = s.execute("mesh.tet.generate", &json!({})).unwrap();
|
||||
let bodies = r["bodies"].as_array().unwrap();
|
||||
@@ -860,7 +898,7 @@ mod tests {
|
||||
#[test]
|
||||
fn quality_summary_counts_invalid_elements() {
|
||||
let mut s = Session::default();
|
||||
assert_eq!(s.execute("mesh.quality", &json!({})).unwrap()["summary"], "no elements to measure");
|
||||
assert!(matches!(s.execute("mesh.quality", &json!({})), Err(crate::EngineError::Unavailable(_))), "no elements to measure");
|
||||
for (label, xyz) in [(1, [0, 0, 0]), (2, [1, 0, 0]), (3, [0, 1, 0]), (4, [0, 0, 1])] {
|
||||
s.execute("mesh.node.add", &json!({"label": label, "xyz": xyz})).unwrap();
|
||||
}
|
||||
@@ -946,8 +984,9 @@ mod tests {
|
||||
|
||||
let p = vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
|
||||
let t = vec![[0, 2, 1], [0, 1, 3], [1, 2, 3], [0, 3, 2]];
|
||||
let tet = SurfaceMesh { positions: p.clone(), triangles: t.clone(), tri_face: vec![0, 1, 1, 1], weld_distance: 0.0 };
|
||||
let open = SurfaceMesh { positions: p, triangles: t[..3].to_vec(), tri_face: vec![0, 1, 1], weld_distance: 0.0 };
|
||||
let tet =
|
||||
SurfaceMesh { positions: p.clone(), triangles: t.clone(), tri_face: vec![0, 1, 1, 1], weld_distance: 0.0, ..SurfaceMesh::default() };
|
||||
let open = SurfaceMesh { positions: p, triangles: t[..3].to_vec(), tri_face: vec![0, 1, 1], weld_distance: 0.0, ..SurfaceMesh::default() };
|
||||
let mut s = Session::default();
|
||||
for mesh in [tet, open] {
|
||||
s.surfaces.push(Arc::new(TaggedSurface { name: "Tet".into(), mesh, faces: 2 }));
|
||||
|
||||
@@ -0,0 +1,408 @@
|
||||
//! `mesh.mirror`: the mesh of some bodies reflected across a plane, joined to them on it.
|
||||
//!
|
||||
//! The geometry tags of the image name what it is the image of: the body of the open design that
|
||||
//! occupies the reflected place (the other half of a part cut on its symmetry plane, found by its
|
||||
//! volume and centroid, or named in `as`), and on it the face each reflected boundary face lies
|
||||
//! on (found by position). Without such a body the image is `<body>/mirror` with the source's
|
||||
//! face names.
|
||||
|
||||
use crate::schema::ProblemKind;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use fieldcraft_geometry::Shape;
|
||||
use fieldcraft_mesh::mirror::{mirror, reflected_edges, reflected_faces};
|
||||
use fieldcraft_model::geometry::Entity;
|
||||
use fieldcraft_model::{ElementFace, GeometryRef, Model};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::requirement::Requirement;
|
||||
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
|
||||
|
||||
pub const MIRROR: CommandSpec = CommandSpec {
|
||||
id: "mesh.mirror",
|
||||
label: "Mirror Mesh",
|
||||
params: r#"{"plane": "Sym" (a datum plane) or {"point": [x, y, z], "normal": [nx, ny, nz]}, "bodies": ["Part/a"] (default: every body the mesh is tagged with), "as": {"Part/a": "Part/b"} (optional: the body each image is; default the design's body at the reflected place, else "<body>/mirror")} — replaces each image body's mesh (as mesh.tet.generate) with the reflection of the bodies' elements (tet4, tet10, wedge6, hex8, hex20) across the plane: each copy right-handed (its nodes in reflected order), the copies of the nodes on the plane merged with them so the mesh is conforming there, geometry tags carried to the image (its body, and on it the faces the reflected faces lie on, so sets by face name select both halves). Reports the elements and nodes added, the nodes shared on the plane and each image's body"#,
|
||||
form: Some(super::forms::MIRROR),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Mesh],
|
||||
run: mirror_mesh,
|
||||
};
|
||||
|
||||
/// Relative difference of volume and centroid (to the body's size) under which a body is the
|
||||
/// image of another.
|
||||
const SAME_PLACE: f64 = 1e-4;
|
||||
|
||||
/// Distance (relative to the mesh's bounding-box diagonal) within which nodes are on the plane.
|
||||
const ON_PLANE: f64 = 1e-7;
|
||||
|
||||
fn not_a_plane() -> EngineError {
|
||||
EngineError::invalid("plane", r#"must be a datum plane's name or {"point": [x, y, z], "normal": [x, y, z]}"#)
|
||||
}
|
||||
|
||||
/// The plane: a datum plane by name, or a point and a normal.
|
||||
fn plane(s: &Session, p: &Value) -> Result<([f64; 3], [f64; 3])> {
|
||||
match p.get("plane") {
|
||||
Some(Value::String(name)) => s
|
||||
.model
|
||||
.datum(name)
|
||||
.and_then(|d| d.plane())
|
||||
.ok_or_else(|| EngineError::Params(format!("no datum plane `{}`", name.chars().take(64).collect::<String>()))),
|
||||
Some(v @ Value::Object(_)) => match (super::xyz(v, "point"), super::xyz(v, "normal")) {
|
||||
(Ok(point), Ok(normal)) => Ok((point, normal)),
|
||||
_ => Err(not_a_plane()),
|
||||
},
|
||||
None | Some(Value::Null) => Err(EngineError::param("plane", ProblemKind::Required)),
|
||||
_ => Err(not_a_plane()),
|
||||
}
|
||||
}
|
||||
|
||||
fn reflect(x: [f64; 3], point: [f64; 3], n: [f64; 3]) -> [f64; 3] {
|
||||
let d: f64 = (0..3).map(|i| (x[i] - point[i]) * n[i]).sum();
|
||||
[x[0] - 2.0 * d * n[0], x[1] - 2.0 * d * n[1], x[2] - 2.0 * d * n[2]]
|
||||
}
|
||||
|
||||
/// The design body at the reflected place of `source`: the same volume and the reflected
|
||||
/// centroid, within [`SAME_PLACE`] (the kernel measures curved bodies on a tessellation, so the
|
||||
/// two halves of a symmetric part measure alike only to its accuracy).
|
||||
fn image_body<'a>(bodies: &'a [Shape], source: &Shape, point: [f64; 3], n: [f64; 3]) -> Result<Option<&'a Shape>> {
|
||||
let m = source.measure()?;
|
||||
let size = source.size()?.max(1e-9);
|
||||
let want = reflect(m.centroid, point, n);
|
||||
for b in bodies.iter().filter(|b| b.name != source.name) {
|
||||
let o = b.measure()?;
|
||||
let d = (0..3).map(|k| (o.centroid[k] - want[k]).powi(2)).sum::<f64>().sqrt();
|
||||
if (o.volume - m.volume).abs() <= SAME_PLACE * m.volume.abs().max(1e-12) && d <= SAME_PLACE * size {
|
||||
return Ok(Some(b));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// What `mesh.mirror` reflects, across which plane, into which bodies.
|
||||
struct Plan<'d> {
|
||||
point: [f64; 3],
|
||||
/// The plane's unit normal.
|
||||
n: [f64; 3],
|
||||
/// The elements reflected.
|
||||
region: BTreeSet<u32>,
|
||||
/// Each mirrored body's image: its name and, when the design has it, its shape.
|
||||
image: BTreeMap<String, (String, Option<&'d Shape>)>,
|
||||
}
|
||||
|
||||
fn plan<'d>(s: &Session, design: Option<&'d fieldcraft_geometry::Design>, p: &Value) -> Result<Plan<'d>> {
|
||||
let (point, normal) = plane(s, p)?;
|
||||
let len = normal.iter().map(|x| x * x).sum::<f64>().sqrt();
|
||||
if !(len > 1e-12 && len.is_finite() && point.iter().all(|x| x.is_finite())) {
|
||||
return Err(EngineError::Params("the plane needs a finite point and a non-zero normal".into()));
|
||||
}
|
||||
let n = normal.map(|x| x / len);
|
||||
let c = s.model.classification();
|
||||
// The bodies the mesh is tagged with, by tag.
|
||||
let tagged: BTreeMap<u32, String> = c
|
||||
.entities()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, r)| r.entity == Entity::Body)
|
||||
.filter_map(|(t, r)| Some((u32::try_from(t).ok()?, r.body.clone())))
|
||||
.collect();
|
||||
let bodies: Vec<String> = match p.get("bodies") {
|
||||
None => {
|
||||
let mut v: Vec<String> = tagged.values().cloned().collect();
|
||||
v.dedup();
|
||||
v
|
||||
}
|
||||
Some(_) => super::req(p, "bodies")?,
|
||||
};
|
||||
if bodies.is_empty() {
|
||||
return Err(EngineError::Params("no body to mirror: the mesh is not tagged with a body".into()));
|
||||
}
|
||||
for b in &bodies {
|
||||
if !tagged.values().any(|t| t == b) {
|
||||
return Err(EngineError::Params(format!("the mesh has no elements of body `{}`", b.chars().take(64).collect::<String>())));
|
||||
}
|
||||
}
|
||||
let named: BTreeMap<String, String> = super::opt(p, "as")?.unwrap_or_default();
|
||||
let region: BTreeSet<u32> =
|
||||
c.elements().iter().filter(|(_, t)| t.region.and_then(|r| tagged.get(&r)).is_some_and(|b| bodies.contains(b))).map(|(e, _)| *e).collect();
|
||||
|
||||
// The image of each body: named, found in the design, or its own `/mirror`.
|
||||
let mut image: BTreeMap<String, (String, Option<&Shape>)> = BTreeMap::new();
|
||||
for b in &bodies {
|
||||
let source = design.and_then(|d| d.body(b));
|
||||
let target = match named.get(b) {
|
||||
Some(t) => (t.clone(), design.and_then(|d| d.body(t))),
|
||||
None => match (design, source) {
|
||||
(Some(d), Some(src)) => match image_body(&d.bodies, src, point, n)? {
|
||||
Some(t) => (t.name.clone(), Some(t)),
|
||||
None => (format!("{b}/mirror"), None),
|
||||
},
|
||||
_ => (format!("{b}/mirror"), None),
|
||||
},
|
||||
};
|
||||
if bodies.contains(&target.0) {
|
||||
return Err(EngineError::Params(format!("the image of `{b}` would be `{}`, which is mirrored too", target.0)));
|
||||
}
|
||||
image.insert(b.clone(), target);
|
||||
}
|
||||
Ok(Plan { point, n, region, image })
|
||||
}
|
||||
|
||||
/// The bodies `mesh.mirror` fills: the images.
|
||||
pub(super) fn image_names(s: &Session, p: &Value) -> Result<Vec<String>> {
|
||||
Ok(plan(s, s.design.as_deref(), p)?.image.into_values().map(|(name, _)| name).collect())
|
||||
}
|
||||
|
||||
fn mirror_mesh(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let design = s.design.clone();
|
||||
let Plan { point, n, region, image } = plan(s, design.as_deref(), p)?;
|
||||
|
||||
let (mut lo, mut hi) = ([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]);
|
||||
for node in s.model.nodes().values() {
|
||||
for k in 0..3 {
|
||||
lo[k] = lo[k].min(node.xyz[k]);
|
||||
hi[k] = hi[k].max(node.xyz[k]);
|
||||
}
|
||||
}
|
||||
let diagonal = (0..3).map(|k| (hi[k] - lo[k]).powi(2)).sum::<f64>().sqrt().max(1e-9);
|
||||
// An image body's earlier mesh is replaced (replace.rs).
|
||||
let model = &mut s.model;
|
||||
let cleared = super::replace::clear(model, image.values().map(|(name, _)| name.as_str()));
|
||||
let before = model.clone();
|
||||
let r = mirror(model, ®ion, point, n, ON_PLANE * diagonal).map_err(|e| EngineError::Params(e.to_string()))?;
|
||||
tag_image(model, &before, &r, &image, point, n, diagonal)?;
|
||||
let added_nodes = model.nodes().len() - before.nodes().len();
|
||||
let images: Vec<Value> = image.iter().map(|(b, (t, shape))| json!({"body": b, "image": t, "in_design": shape.is_some()})).collect();
|
||||
let reply = json!({
|
||||
"elements": r.elements.len(),
|
||||
"nodes": added_nodes,
|
||||
"on_plane": r.on_plane,
|
||||
"images": images,
|
||||
"total": {"nodes": s.model.nodes().len(), "elements": s.model.elements().len()},
|
||||
});
|
||||
Ok(cleared.report(s, reply))
|
||||
}
|
||||
|
||||
/// Tag the image: each copy with its image body, its faces with the faces of that body they lie
|
||||
/// on (or the source's names), its edges and the images of tagged nodes with the source's names.
|
||||
fn tag_image(
|
||||
model: &mut Model,
|
||||
before: &Model,
|
||||
r: &fieldcraft_mesh::mirror::Mirrored,
|
||||
image: &BTreeMap<String, (String, Option<&Shape>)>,
|
||||
point: [f64; 3],
|
||||
n: [f64; 3],
|
||||
diagonal: f64,
|
||||
) -> Result<()> {
|
||||
let c = before.classification();
|
||||
let entity = |t: u32| c.entity(t).cloned();
|
||||
// A source face's image: by the image body's face under its reflected centroid, one lookup per
|
||||
// face name (the first element face of it stands for all).
|
||||
let mut face_points: BTreeMap<(String, String), [f64; 3]> = BTreeMap::new();
|
||||
for (&e, tags) in c.elements() {
|
||||
if !r.elements.contains_key(&e) {
|
||||
continue;
|
||||
}
|
||||
for (&f, &t) in &tags.faces {
|
||||
let Some(GeometryRef { body, entity: Entity::Face(name) }) = entity(t) else { continue };
|
||||
if face_points.contains_key(&(body.clone(), name.clone())) {
|
||||
continue;
|
||||
}
|
||||
let Some(nodes) = before.face_nodes(ElementFace { element: e, face: f }) else { continue };
|
||||
let pts: Vec<[f64; 3]> = nodes.iter().filter_map(|n| before.node(*n).map(|x| x.xyz)).collect();
|
||||
let k = pts.len().max(1) as f64;
|
||||
let centre = [0, 1, 2].map(|i| pts.iter().map(|p| p[i]).sum::<f64>() / k);
|
||||
face_points.insert((body, name), reflect(centre, point, n));
|
||||
}
|
||||
}
|
||||
let mut face_names: BTreeMap<(String, String), (String, String)> = BTreeMap::new();
|
||||
let mut by_body: BTreeMap<String, Vec<(String, [f64; 3])>> = BTreeMap::new();
|
||||
for ((body, name), p) in &face_points {
|
||||
by_body.entry(body.clone()).or_default().push((name.clone(), *p));
|
||||
}
|
||||
for (body, faces) in by_body {
|
||||
let Some((target, shape)) = image.get(&body) else { continue };
|
||||
let found = match shape {
|
||||
Some(shape) => {
|
||||
let pts: Vec<[f64; 3]> = faces.iter().map(|(_, p)| *p).collect();
|
||||
shape.nearest_faces(&pts, (1e-3 * diagonal).max(1e-4))?
|
||||
}
|
||||
None => vec![None; faces.len()],
|
||||
};
|
||||
for ((name, _), f) in faces.iter().zip(found) {
|
||||
let mapped = f.and_then(|f| shape.and_then(|s| s.faces().get(f as usize))).map_or_else(|| name.clone(), |x| x.name.clone());
|
||||
face_names.insert((body.clone(), name.clone()), (target.clone(), mapped));
|
||||
}
|
||||
}
|
||||
let mut tags: BTreeMap<GeometryRef, u32> = BTreeMap::new();
|
||||
let mut tag = |model: &mut Model, r: GeometryRef| -> Result<u32> {
|
||||
if let Some(&t) = tags.get(&r) {
|
||||
return Ok(t);
|
||||
}
|
||||
let t = model.geometry_tag(&r)?;
|
||||
tags.insert(r, t);
|
||||
Ok(t)
|
||||
};
|
||||
for (&e, ©) in &r.elements {
|
||||
let Some(el) = before.element(e) else { continue };
|
||||
let Some(t) = c.elements().get(&e) else { continue };
|
||||
let faces = reflected_faces(el.kind).unwrap_or_default();
|
||||
let edges = reflected_edges(el.kind).unwrap_or_default();
|
||||
if let Some(GeometryRef { body, .. }) = t.region.and_then(entity)
|
||||
&& let Some((target, _)) = image.get(&body)
|
||||
{
|
||||
let tg = tag(model, GeometryRef::body(target.as_str())?)?;
|
||||
model.tag_element(copy, tg)?;
|
||||
}
|
||||
for (&f, &ft) in &t.faces {
|
||||
let Some(GeometryRef { body, entity: Entity::Face(name) }) = entity(ft) else { continue };
|
||||
let Some((tb, tn)) = face_names.get(&(body, name)) else { continue };
|
||||
let g = faces.get(usize::from(f).saturating_sub(1)).copied().unwrap_or(f);
|
||||
let tg = tag(model, GeometryRef::face(tb.as_str(), tn.as_str())?)?;
|
||||
model.tag_element_face(copy, g, tg)?;
|
||||
}
|
||||
for (&k, &et) in &t.edges {
|
||||
let Some(GeometryRef { body, entity: ent }) = entity(et) else { continue };
|
||||
let Some((target, _)) = image.get(&body) else { continue };
|
||||
let g = edges.get(usize::from(k).saturating_sub(1)).copied().unwrap_or(k);
|
||||
let tg = tag(model, GeometryRef::new(target.as_str(), ent)?)?;
|
||||
model.tag_element_edge(copy, g, tg)?;
|
||||
}
|
||||
}
|
||||
for (&node, ©) in &r.nodes {
|
||||
if copy == node {
|
||||
continue;
|
||||
}
|
||||
let Some(GeometryRef { body, entity: ent }) = c.nodes().get(&node).and_then(|&t| entity(t)) else { continue };
|
||||
let Some((target, _)) = image.get(&body) else { continue };
|
||||
let tg = tag(model, GeometryRef::new(target.as_str(), ent)?)?;
|
||||
model.tag_node(copy, tg)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A session with a 40 × 10 × 10 bar (along x from the origin) open, partitioned at
|
||||
/// x = 20 when `half`.
|
||||
fn bar(half: bool) -> (crate::tests::TempDir, Session) {
|
||||
let commands = json!({"commands": [
|
||||
{"command": "solid.box", "params": {"length": 40, "width": 10, "height": 10, "body_name": "Bar"}},
|
||||
]});
|
||||
let bytes = fieldcraft_geometry::script_design(&commands.to_string()).unwrap();
|
||||
let (dir, path) = crate::tests::design_file(&bytes);
|
||||
let mut s = Session::default();
|
||||
s.execute("geometry.open", &json!({"path": path})).unwrap();
|
||||
let b = s.execute("geometry.bodies", &json!({})).unwrap()[0]["bbox"].clone();
|
||||
let lo: Vec<f64> = b[0].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
|
||||
let hi: Vec<f64> = b[1].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
|
||||
assert_eq!(lo, [0.0; 3]);
|
||||
assert_eq!(hi, [40.0, 10.0, 10.0]);
|
||||
s.execute("geometry.datum", &json!({"name": "Mid", "by": {"type": "offset", "plane": "yz", "offset": 20}})).unwrap();
|
||||
if half {
|
||||
s.execute("geometry.partition", &json!({"name": "Half", "datum": "Mid"})).unwrap();
|
||||
}
|
||||
(dir, s)
|
||||
}
|
||||
|
||||
/// The face of `body` nearest to `point`.
|
||||
fn face(s: &Session, body: &str, point: [f64; 3]) -> String {
|
||||
let shape = s.design.as_ref().unwrap().body(body).unwrap();
|
||||
let f = shape.nearest_faces(&[point], 0.01).unwrap()[0].unwrap();
|
||||
shape.faces()[f as usize].name.clone()
|
||||
}
|
||||
|
||||
/// Clamped at x = 0, 1 kN down on the end at x = 40 (sets by face name on the bodies given),
|
||||
/// solved; the largest downward deflection and the mesh's volume and counts.
|
||||
fn bend(s: &mut Session, root: (&str, String), tip: (&str, String)) -> (f64, f64, usize, usize) {
|
||||
let all: Vec<Value> = s.design.as_ref().unwrap().bodies.iter().map(|b| json!({"body": b.name})).collect();
|
||||
let script = json!([
|
||||
{"command": "model.set.create", "params": {"name": "all", "geometry": all}},
|
||||
{"command": "model.set.create", "params": {"name": "root", "geometry": [{"body": root.0, "face": root.1}]}},
|
||||
{"command": "model.set.create", "params": {"name": "tip", "geometry": [{"body": tip.0, "face": tip.1}]}},
|
||||
{"command": "model.material.create", "params": {"name": "Steel", "elastic": {"type": "isotropic", "young": 210000, "poisson": 0.3}}},
|
||||
{"command": "model.section.create", "params": {"name": "Bar", "set": "all", "material": "Steel", "kind": {"type": "solid"}}},
|
||||
{"command": "model.boundary_condition.create", "params": {"name": "Clamp", "type": "fixed", "target": {"set": "root"}}},
|
||||
{"command": "model.load.create", "params": {"name": "Push", "type": "force", "target": {"set": "tip"}, "vector": [0, 0, -1000]}},
|
||||
{"command": "model.step.create", "params": {"name": "Load", "procedure": {"type": "static"}, "boundary_conditions": ["Clamp"], "loads": ["Push"]}},
|
||||
]);
|
||||
s.run_script(&script).unwrap();
|
||||
s.execute("solve.static", &json!({})).unwrap();
|
||||
let tip_nodes = s.model.resolve_set("tip").unwrap().nodes;
|
||||
assert!(!tip_nodes.is_empty());
|
||||
let probe = s.execute("solve.probe", &json!({"step": "Load", "nodes": tip_nodes})).unwrap();
|
||||
let w = probe["nodes"].as_array().unwrap().iter().map(|n| -n["displacement"][2].as_f64().unwrap()).fold(f64::MIN, f64::max);
|
||||
let q = s.execute("mesh.quality", &json!({})).unwrap();
|
||||
assert_eq!(q["valid"].as_u64().unwrap() as usize, s.model.elements().len(), "{q}");
|
||||
(w, q["volume"].as_f64().unwrap(), s.model.nodes().len(), s.model.elements().len())
|
||||
}
|
||||
|
||||
/// Half the bar meshed and mirrored is the whole bar meshed: the same counts and volume, and
|
||||
/// the same bending deflection to round-off, hex8 and hex20; the image's faces carry the
|
||||
/// whole bar's face names, so the load on the far end (a face of the image only) is found.
|
||||
#[test]
|
||||
fn a_mirrored_half_is_the_whole_mesh() {
|
||||
for order in [1, 2] {
|
||||
let (_d1, mut whole) = bar(false);
|
||||
whole.execute("mesh.hex.mapped", &json!({"body": "Bar", "size": 2.5, "order": order})).unwrap();
|
||||
let (root, tip) = (face(&whole, "Bar", [0.0, 5.0, 5.0]), face(&whole, "Bar", [40.0, 5.0, 5.0]));
|
||||
let full = bend(&mut whole, ("Bar", root), ("Bar", tip));
|
||||
|
||||
let (_d2, mut half) = bar(true);
|
||||
half.execute("mesh.hex.mapped", &json!({"body": "Bar/a", "size": 2.5, "order": order})).unwrap();
|
||||
let r = half.execute("mesh.mirror", &json!({"plane": "Mid"})).unwrap();
|
||||
assert_eq!(r["images"][0], json!({"body": "Bar/a", "image": "Bar/b", "in_design": true}), "{r}");
|
||||
// 5 × 5 corner nodes on the plane (and 40 mid-edge nodes on it for hex20).
|
||||
assert_eq!(r["on_plane"], json!(if order == 1 { 25 } else { 65 }), "{r}");
|
||||
let (root, tip) = (face(&half, "Bar/a", [0.0, 5.0, 5.0]), face(&half, "Bar/b", [40.0, 5.0, 5.0]));
|
||||
let mirrored = bend(&mut half, ("Bar/a", root), ("Bar/b", tip));
|
||||
assert_eq!((mirrored.2, mirrored.3), (full.2, full.3), "order {order}: node and element counts");
|
||||
assert!((mirrored.1 - full.1).abs() < 1e-9 * full.1, "order {order}: volume {} vs {}", mirrored.1, full.1);
|
||||
assert!((mirrored.0 - full.0).abs() < 1e-9 * full.0, "order {order}: deflection {} vs {}", mirrored.0, full.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Tets of either order mirror into valid elements sharing the plane's nodes; the volume
|
||||
/// doubles.
|
||||
#[test]
|
||||
fn mirrored_tets_are_valid_and_conforming() {
|
||||
for order in ["linear", "quadratic"] {
|
||||
let (_d, mut s) = bar(true);
|
||||
s.execute("mesh.tet.generate", &json!({"body": "Bar/a", "size": 4, "order": order})).unwrap();
|
||||
let v = s.execute("mesh.quality", &json!({})).unwrap()["volume"].as_f64().unwrap();
|
||||
let r = s.execute("mesh.mirror", &json!({"plane": {"point": [20, 0, 0], "normal": [1, 0, 0]}, "bodies": ["Bar/a"]})).unwrap();
|
||||
assert!(r["on_plane"].as_u64().unwrap() > 0, "{r}");
|
||||
let q = s.execute("mesh.quality", &json!({})).unwrap();
|
||||
assert_eq!(q["valid"].as_u64().unwrap() as usize, s.model.elements().len(), "{q}");
|
||||
assert!((q["volume"].as_f64().unwrap() - 2.0 * v).abs() < 1e-9 * v, "{q}");
|
||||
// The plane's faces are interior now: the skin of both bodies is the bar's.
|
||||
s.execute("model.set.create", &json!({"name": "a", "geometry": [{"body": "Bar/a"}]})).unwrap();
|
||||
s.execute("model.set.create", &json!({"name": "b", "geometry": [{"body": "Bar/b"}]})).unwrap();
|
||||
let (a, b) = (s.model.resolve_set("a").unwrap(), s.model.resolve_set("b").unwrap());
|
||||
assert_eq!(a.elements.len(), b.elements.len());
|
||||
assert_eq!(a.faces.len(), b.faces.len());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_params_change_nothing() {
|
||||
let (_d, mut s) = bar(true);
|
||||
s.execute("mesh.hex.mapped", &json!({"body": "Bar/a", "size": 5})).unwrap();
|
||||
let model = s.model.clone();
|
||||
for p in [
|
||||
json!({}),
|
||||
json!({"plane": "Nope"}),
|
||||
json!({"plane": {"point": [0, 0, 0], "normal": [0, 0, 0]}}),
|
||||
json!({"plane": {"point": [f64::MAX, 0, 0], "normal": [1, 0, 0]}}),
|
||||
json!({"plane": {"point": [0, 0], "normal": [1, 0, 0]}}),
|
||||
json!({"plane": "Mid", "bodies": ["Nope"]}),
|
||||
json!({"plane": "Mid", "bodies": []}),
|
||||
json!({"plane": "Mid", "as": {"Bar/a": "Bar/a"}}),
|
||||
json!({"plane": "Mid", "as": "x"}),
|
||||
] {
|
||||
assert!(s.execute("mesh.mirror", &p).is_err(), "{p}");
|
||||
}
|
||||
assert_eq!(s.model, model);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
//! The command registry. Each area has its own module; [`ALL`] lists every command.
|
||||
|
||||
mod block;
|
||||
mod cells;
|
||||
mod contact;
|
||||
pub(crate) mod datum;
|
||||
pub(crate) mod deck;
|
||||
pub(crate) mod define;
|
||||
pub mod diagnostics;
|
||||
mod edit;
|
||||
pub(crate) mod file;
|
||||
pub(crate) mod forms;
|
||||
@@ -11,13 +14,21 @@ mod geometry;
|
||||
mod hex;
|
||||
pub(crate) mod mesh;
|
||||
|
||||
pub use datum::edit_params as datum_edit_params;
|
||||
pub use mesh::analytic_surfaces;
|
||||
mod mirror;
|
||||
mod model;
|
||||
pub(crate) mod octree;
|
||||
pub mod replace;
|
||||
mod results;
|
||||
pub(crate) mod seeds;
|
||||
pub(crate) mod solve;
|
||||
mod symmetry;
|
||||
mod tags;
|
||||
pub mod update;
|
||||
pub(crate) mod view;
|
||||
|
||||
use crate::schema::ProblemKind;
|
||||
use fieldcraft_model::MAX_LABEL;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
@@ -32,6 +43,19 @@ pub static ALL: &[CommandSpec] = &[
|
||||
geometry::BODIES,
|
||||
geometry::TESSELLATE,
|
||||
geometry::IMPORT_MESH,
|
||||
datum::DATUM_PLANE,
|
||||
datum::DATUM_AXIS,
|
||||
datum::DATUM_POINT,
|
||||
datum::DATUM_EDIT,
|
||||
datum::DATUM_AXIS_EDIT,
|
||||
datum::DATUM_POINT_EDIT,
|
||||
datum::DATUM_DELETE,
|
||||
view::HIDE,
|
||||
view::SHOW,
|
||||
view::ISOLATE,
|
||||
view::SHOW_ALL,
|
||||
datum::PARTITION,
|
||||
datum::PARTITION_DELETE,
|
||||
mesh::NODE_ADD,
|
||||
mesh::NODE_REMOVE,
|
||||
mesh::ELEMENT_ADD,
|
||||
@@ -47,6 +71,11 @@ pub static ALL: &[CommandSpec] = &[
|
||||
hex::HEX_SWEEP,
|
||||
hex::HEX_MAPPED,
|
||||
hex::HEX_BLOCKS,
|
||||
cells::CELLS,
|
||||
seeds::SEED_EDGE,
|
||||
seeds::SEED_CLEAR,
|
||||
seeds::SEED_LIST,
|
||||
mirror::MIRROR,
|
||||
tags::TAG,
|
||||
tags::TAG_CLEAR,
|
||||
model::UNITS,
|
||||
@@ -86,6 +115,7 @@ pub static ALL: &[CommandSpec] = &[
|
||||
define::BOUNDARY_CONDITION_CREATE,
|
||||
define::BOUNDARY_CONDITION_EDIT,
|
||||
define::BOUNDARY_CONDITION_DELETE,
|
||||
symmetry::SYMMETRY,
|
||||
define::LOAD_CREATE,
|
||||
define::LOAD_EDIT,
|
||||
define::LOAD_DELETE,
|
||||
@@ -125,14 +155,25 @@ pub static ALL: &[CommandSpec] = &[
|
||||
results::FRAME,
|
||||
results::REACTIONS,
|
||||
results::CLEAR,
|
||||
diagnostics::CRASH_REPORTS,
|
||||
diagnostics::CRASH_REPORT,
|
||||
diagnostics::BUG_REPORT,
|
||||
diagnostics::CRASH_TEST,
|
||||
update::CHECK,
|
||||
];
|
||||
|
||||
/// The problem with required parameter `key`: [`ProblemKind::Required`] when it is left out,
|
||||
/// else `kind`.
|
||||
pub(crate) fn wrong(p: &Value, key: &str, kind: ProblemKind) -> EngineError {
|
||||
EngineError::param(key, if p.get(key).is_none_or(Value::is_null) { ProblemKind::Required } else { kind })
|
||||
}
|
||||
|
||||
/// A required label parameter (1..=u32::MAX; the model checks its own range).
|
||||
pub(crate) fn label(p: &Value, key: &str) -> Result<u32> {
|
||||
p.get(key)
|
||||
.and_then(Value::as_u64)
|
||||
.and_then(|v| u32::try_from(v).ok())
|
||||
.ok_or_else(|| EngineError::Params(format!("`{key}` must be a positive whole number")))
|
||||
.ok_or_else(|| wrong(p, key, ProblemKind::NotAWholeNumber { min: 1, max: i64::from(u32::MAX) }))
|
||||
}
|
||||
|
||||
/// The first node and element labels after the model's largest, for `nodes` new nodes and
|
||||
@@ -150,7 +191,7 @@ pub(crate) fn fresh_labels(model: &fieldcraft_model::Model, nodes: usize, elemen
|
||||
|
||||
/// A required `[x, y, z]` parameter.
|
||||
pub(crate) fn xyz(p: &Value, key: &str) -> Result<[f64; 3]> {
|
||||
p.get(key).and_then(xyz_value).ok_or_else(|| EngineError::Params(format!("`{key}` must be [x, y, z]")))
|
||||
p.get(key).and_then(xyz_value).ok_or_else(|| wrong(p, key, ProblemKind::NotAVector { len: 3 }))
|
||||
}
|
||||
|
||||
/// A JSON `[x, y, z]`.
|
||||
@@ -163,9 +204,12 @@ fn xyz_value(v: &Value) -> Option<[f64; 3]> {
|
||||
|
||||
/// A required list of `[x, y, z]` points, at most `max_len` long.
|
||||
pub(crate) fn points(p: &Value, key: &str, max_len: usize) -> Result<Vec<[f64; 3]>> {
|
||||
let bad = |what: String| EngineError::Params(format!("`{key}` must be a list of at most {max_len} [x, y, z]{what}"));
|
||||
let raw = p.get(key).and_then(Value::as_array).filter(|a| a.len() <= max_len).ok_or_else(|| bad(String::new()))?;
|
||||
raw.iter().enumerate().map(|(i, v)| xyz_value(v).ok_or_else(|| bad(format!(" (entry {i} is not)")))).collect()
|
||||
let raw = p.get(key).and_then(Value::as_array).filter(|a| a.len() <= max_len);
|
||||
let raw = raw.ok_or_else(|| wrong(p, key, ProblemKind::NotAList { max: max_len, what: "[x, y, z]" }))?;
|
||||
raw.iter()
|
||||
.enumerate()
|
||||
.map(|(i, v)| xyz_value(v).ok_or_else(|| EngineError::invalid(key, format!("must be a list of [x, y, z] (entry {i} is not)"))))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A required list of labels (each in 1..=MAX_LABEL), at most `max_len` long.
|
||||
@@ -174,11 +218,11 @@ pub(crate) fn labels(p: &Value, key: &str, max_len: usize) -> Result<Vec<u32>> {
|
||||
.get(key)
|
||||
.and_then(Value::as_array)
|
||||
.filter(|a| a.len() <= max_len)
|
||||
.ok_or_else(|| EngineError::Params(format!("`{key}` must be a list of at most {max_len} labels")))?;
|
||||
.ok_or_else(|| wrong(p, key, ProblemKind::NotAList { max: max_len, what: "labels" }))?;
|
||||
raw.iter()
|
||||
.map(|v| v.as_u64().and_then(|n| u32::try_from(n).ok()).filter(|n| (1..=MAX_LABEL).contains(n)))
|
||||
.collect::<Option<Vec<u32>>>()
|
||||
.ok_or_else(|| EngineError::Params(format!("`{key}` must be labels in 1..={MAX_LABEL}")))
|
||||
.ok_or_else(|| EngineError::invalid(key, format!("must be labels in 1..={MAX_LABEL}")))
|
||||
}
|
||||
|
||||
/// A required path parameter, as given.
|
||||
@@ -186,7 +230,7 @@ fn path_param<'a>(p: &'a Value, key: &str) -> Result<&'a str> {
|
||||
p.get(key)
|
||||
.and_then(Value::as_str)
|
||||
.filter(|s| !s.trim().is_empty() && s.len() <= fieldcraft_io::MAX_PATH_LEN && !s.contains('\0'))
|
||||
.ok_or_else(|| EngineError::Params(format!("`{key}` must be a file path")))
|
||||
.ok_or_else(|| wrong(p, key, ProblemKind::NotAPath))
|
||||
}
|
||||
|
||||
/// A required path parameter naming a file (or folder) the command reads or writes: the path
|
||||
@@ -201,23 +245,23 @@ pub(crate) fn file_param(s: &Session, p: &Value, key: &str, access: Access) -> R
|
||||
pub(crate) fn optional_number(p: &Value, key: &str, default: f64) -> Result<f64> {
|
||||
match p.get(key) {
|
||||
None => Ok(default),
|
||||
Some(v) => v.as_f64().ok_or_else(|| EngineError::Params(format!("`{key}` must be a number"))),
|
||||
Some(v) => v.as_f64().ok_or_else(|| EngineError::param(key, ProblemKind::NotANumber)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `name` parameter.
|
||||
pub(crate) fn name(p: &Value) -> Result<&str> {
|
||||
p.get("name").and_then(Value::as_str).ok_or_else(|| EngineError::Params("`name` must be a name".into()))
|
||||
p.get("name").and_then(Value::as_str).ok_or_else(|| wrong(p, "name", ProblemKind::NotAName))
|
||||
}
|
||||
|
||||
/// An optional parameter read as `T`'s JSON form; `None` when it is absent.
|
||||
pub(crate) fn opt<'a, T: Deserialize<'a>>(p: &'a Value, key: &str) -> Result<Option<T>> {
|
||||
p.get(key).map(|v| T::deserialize(v).map_err(|e| EngineError::Params(format!("`{key}`: {e}")))).transpose()
|
||||
p.get(key).map(|v| T::deserialize(v).map_err(|e| EngineError::invalid(key, format!("is not valid: {e}")))).transpose()
|
||||
}
|
||||
|
||||
/// A required parameter read as `T`'s JSON form.
|
||||
pub(crate) fn req<'a, T: Deserialize<'a>>(p: &'a Value, key: &str) -> Result<T> {
|
||||
opt(p, key)?.ok_or_else(|| EngineError::Params(format!("`{key}` is required")))
|
||||
opt(p, key)?.ok_or_else(|| EngineError::param(key, ProblemKind::Required))
|
||||
}
|
||||
|
||||
/// Entries listed in a report: the first ones, and how many there are.
|
||||
|
||||
@@ -2,10 +2,11 @@ use fieldcraft_model::{Severity, UnitSystem};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{listed, name};
|
||||
use crate::requirement::Requirement;
|
||||
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
|
||||
|
||||
pub const INFO: CommandSpec =
|
||||
CommandSpec { id: "model.info", label: "Model Info", params: "{}", form: Some(&[]), kind: CommandKind::Model, run: info };
|
||||
CommandSpec { id: "model.info", label: "Model Info", params: "{}", form: Some(&[]), kind: CommandKind::Model, requires: &[], run: info };
|
||||
|
||||
pub const UNITS: CommandSpec = CommandSpec {
|
||||
id: "model.units",
|
||||
@@ -13,11 +14,12 @@ pub const UNITS: CommandSpec = CommandSpec {
|
||||
params: r#"{"system": "m-kg-s-N-Pa|mm-t-s-N-MPa|mm-kg-ms-kN-GPa|mm-g-ms-N-MPa|in-lbf-s-psi|unspecified"} — labels the system the model's numbers are in; nothing is converted"#,
|
||||
form: Some(super::forms::UNITS),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[],
|
||||
run: units,
|
||||
};
|
||||
|
||||
pub const CHECK: CommandSpec =
|
||||
CommandSpec { id: "model.check", label: "Check Model", params: "{}", form: Some(&[]), kind: CommandKind::Model, run: check };
|
||||
CommandSpec { id: "model.check", label: "Check Model", params: "{}", form: Some(&[]), kind: CommandKind::Model, requires: &[], run: check };
|
||||
|
||||
pub const SET_RESOLVE: CommandSpec = CommandSpec {
|
||||
id: "model.set.resolve",
|
||||
@@ -25,6 +27,7 @@ pub const SET_RESOLVE: CommandSpec = CommandSpec {
|
||||
params: r#"{"name": "root"} — the set's nodes, elements and element faces on the current mesh (the first 100 of each); fails naming every member that is not on the mesh"#,
|
||||
form: Some(super::forms::SET_RESOLVE),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Set],
|
||||
run: set_resolve,
|
||||
};
|
||||
|
||||
@@ -54,11 +57,14 @@ fn units(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn check(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let diagnostics = s.model.check();
|
||||
let errors = diagnostics.iter().filter(|d| d.severity == Severity::Error).count();
|
||||
let first_error = diagnostics.iter().find(|d| d.severity == Severity::Error).map(ToString::to_string);
|
||||
let progress = crate::progress::to_json(&s.progress_given(first_error));
|
||||
Ok(json!({
|
||||
"ready": errors == 0,
|
||||
"errors": errors,
|
||||
"warnings": diagnostics.len() - errors,
|
||||
"diagnostics": diagnostics,
|
||||
"progress": progress,
|
||||
}))
|
||||
}
|
||||
|
||||
|
||||
@@ -9,14 +9,16 @@ use serde_json::{Value, json};
|
||||
|
||||
use super::hex::{Input, inputs, number, tag_faces};
|
||||
use super::mesh::optional_count;
|
||||
use crate::requirement::Requirement;
|
||||
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
|
||||
|
||||
pub const HEX_OCTREE: CommandSpec = CommandSpec {
|
||||
id: "mesh.hex.octree",
|
||||
label: "Octree Hex Mesh",
|
||||
params: r#"{"body": "Body1" (default: every body of the open design) or "surface": 0 (an imported surface), "size": 2.0 (element size in the interior, mm; default 1/25 of the bounding-box diagonal), "tolerance": 0.05 (chordal tolerance of the tessellation, mm; default 1e-3 of the diagonal), "max_depth": 3 (refinement levels below the size, each a third, 0..=5), "max_elements": 2000000 (1..=10000000; default the session limit), "attempts": 4 (builds, refining where one failed, 1..=8), "max_sweeps": 300 (optimiser sweeps, 0..=10000), and the boundary options of mesh.tet.generate ("weld", "weld_distance", "feature_angle")} — replaces the mesh with an unstructured all-hex8 mesh of any part: an adaptive 3-refinement grid with conforming transition templates, a core inside the part, two boundary layers that capture every B-rep face boundary and sharp edge, and untangling. Every element is proven valid; boundary element faces are tagged with their B-rep faces (named as in geometry.bodies; by index when a face has no name), so sets by geometry resolve. Reports per body the elements, quality, volume and grid statistics"#,
|
||||
params: r#"{"body": "Body1" (default: every body of the open design) or "surface": 0 (an imported surface), "size": 2.0 (element size in the interior, mm; default 1/25 of the bounding-box diagonal), "tolerance": 0.05 (chordal tolerance of the tessellation, mm; default 1e-3 of the diagonal), "max_depth": 3 (refinement levels below the size, each a third, 0..=5), "max_elements": 2000000 (1..=10000000; default the session limit), "attempts": 4 (builds, refining where one failed, 1..=8), "max_sweeps": 300 (optimiser sweeps, 0..=10000), and the boundary options of mesh.tet.generate ("weld", "weld_distance", "feature_angle")} — replaces the meshes of the bodies it meshes (as mesh.tet.generate; other bodies keep theirs) with an unstructured all-hex8 mesh of any part: an adaptive 3-refinement grid with conforming transition templates, a core inside the part, two boundary layers that capture every B-rep face boundary and sharp edge, and untangling. Every element is proven valid; boundary element faces are tagged with their B-rep faces (named as in geometry.bodies; by index when a face has no name), so sets by geometry resolve. Reports per body the elements, quality, volume and grid statistics"#,
|
||||
form: Some(super::forms::HEX_OCTREE),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Geometry],
|
||||
run: hex_octree,
|
||||
};
|
||||
|
||||
@@ -62,22 +64,20 @@ fn hex_octree(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
total += mesh.hexes.len();
|
||||
meshes.push((b, mesh));
|
||||
}
|
||||
// Replace the mesh: definitions stay, nodes, elements and geometry tags are new.
|
||||
let mut model = s.model.without_mesh();
|
||||
// Replace the bodies' meshes (replace.rs); other bodies and the definitions stay.
|
||||
let mut model = s.model.clone();
|
||||
let cleared = super::replace::clear(&mut model, meshes.iter().map(|(b, _)| b.name.as_str()));
|
||||
let mut report = Vec::with_capacity(meshes.len());
|
||||
let (mut node_label, mut element_label) = (1u32, 1u32);
|
||||
for (b, m) in &meshes {
|
||||
let first_node = node_label;
|
||||
for xyz in &m.nodes {
|
||||
model.set_node(node_label, *xyz)?;
|
||||
node_label = node_label.checked_add(1).ok_or_else(|| EngineError::Params("too many nodes".into()))?;
|
||||
let (first_node, first_element) = super::fresh_labels(&model, m.nodes.len(), m.hexes.len())?;
|
||||
for (i, xyz) in m.nodes.iter().enumerate() {
|
||||
model.set_node(first_node + i as u32, *xyz)?;
|
||||
}
|
||||
let body_tag = model.geometry_tag(&GeometryRef::body(b.name.as_str())?)?;
|
||||
let first_element = element_label;
|
||||
for hx in &m.hexes {
|
||||
model.set_element(element_label, ElementKind::Hex8, hx.iter().map(|&i| first_node + i).collect())?;
|
||||
model.tag_element(element_label, body_tag)?;
|
||||
element_label = element_label.checked_add(1).ok_or_else(|| EngineError::Params("too many elements".into()))?;
|
||||
for (i, hx) in m.hexes.iter().enumerate() {
|
||||
let l = first_element + i as u32;
|
||||
model.set_element(l, ElementKind::Hex8, hx.iter().map(|&i| first_node + i).collect())?;
|
||||
model.tag_element(l, body_tag)?;
|
||||
}
|
||||
tag_faces(&mut model, std::slice::from_ref(b), |_| 0, &m.boundary, first_element)?;
|
||||
let r = &m.report;
|
||||
@@ -97,8 +97,9 @@ fn hex_octree(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"sweeps": r.sweeps,
|
||||
}));
|
||||
}
|
||||
let (nodes, elements) = (model.nodes().len(), model.elements().len());
|
||||
s.model = model;
|
||||
Ok(json!({"bodies": report, "nodes": node_label - 1, "elements": element_label - 1}))
|
||||
Ok(cleared.report(s, json!({"bodies": report, "nodes": nodes, "elements": elements})))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
//! Meshing a body replaces its mesh (#267). Every mesher that fills bodies goes through
|
||||
//! [`clear`]: before it adds a body's new elements it removes that body's old elements and the
|
||||
//! nodes only they use, so other bodies keep their meshes and two meshes never stack on one
|
||||
//! body. The reply's `replaced` says what went; sets that listed the removed labels are named as
|
||||
//! `stale_sets` (sets by geometry re-resolve on the new mesh), and results solved on the old
|
||||
//! mesh as `results_cleared`. The command is one undo step, so undo brings the old mesh back.
|
||||
//!
|
||||
//! [`MESHERS`] lists those commands with the bodies each one fills, which the UI reads
|
||||
//! ([`replacement`]) to ask before replacing a mesh. Programmatic calls never ask. `mesh.block`
|
||||
//! is not one of them: a body is built from several blocks, each call adding one.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use fieldcraft_model::{BodyMesh, ElementKind, Model};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
/// What [`clear`] removed.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Cleared {
|
||||
/// Per body that had a mesh: its name and the element and node counts removed.
|
||||
bodies: Vec<(String, usize, usize)>,
|
||||
removed: BodyMesh,
|
||||
/// Sets that listed a removed node or element by label.
|
||||
stale_sets: Vec<String>,
|
||||
}
|
||||
|
||||
/// Remove the meshes of `bodies` from `model` (each body once).
|
||||
pub(super) fn clear<'a>(model: &mut Model, bodies: impl IntoIterator<Item = &'a str>) -> Cleared {
|
||||
let mut out = Cleared::default();
|
||||
let mut seen = BTreeSet::new();
|
||||
for body in bodies {
|
||||
if !seen.insert(body) {
|
||||
continue;
|
||||
}
|
||||
let r = model.remove_body_mesh(body);
|
||||
if !r.elements.is_empty() {
|
||||
out.bodies.push((body.to_string(), r.elements.len(), r.nodes.len()));
|
||||
out.removed.elements.extend(r.elements);
|
||||
out.removed.nodes.extend(r.nodes);
|
||||
}
|
||||
}
|
||||
out.stale_sets = model.sets_using(&out.removed);
|
||||
out
|
||||
}
|
||||
|
||||
impl Cleared {
|
||||
/// Add `replaced`, `stale_sets` and `results_cleared` to a command's reply (an object).
|
||||
pub(super) fn report(self, s: &Session, mut reply: Value) -> Value {
|
||||
if let Some(o) = reply.as_object_mut() {
|
||||
let replaced: Vec<Value> = self.bodies.iter().map(|(b, e, n)| json!({"body": b, "elements": e, "nodes": n})).collect();
|
||||
o.insert("replaced".into(), json!(replaced));
|
||||
if !self.stale_sets.is_empty() {
|
||||
o.insert("stale_sets".into(), json!(self.stale_sets));
|
||||
}
|
||||
let results: Vec<&str> = s.solved_steps().collect();
|
||||
if !results.is_empty() {
|
||||
o.insert("results_cleared".into(), json!(results));
|
||||
}
|
||||
}
|
||||
reply
|
||||
}
|
||||
}
|
||||
|
||||
/// The bodies a meshing command fills, from its parameters, without meshing anything.
|
||||
pub type Targets = fn(&Session, &Value) -> Result<Vec<String>>;
|
||||
|
||||
/// Every command that fills bodies with a mesh and replaces theirs, with the bodies it fills.
|
||||
pub static MESHERS: &[(&str, Targets)] = &[
|
||||
("mesh.tet.generate", body_or_all),
|
||||
("mesh.hex.generate", body_or_all),
|
||||
("mesh.hex.sweep", body_or_all),
|
||||
("mesh.hex.mapped", body_or_all),
|
||||
("mesh.hex.octree", body_or_all),
|
||||
("mesh.hex.blocks", listed_or_all),
|
||||
("mesh.cells", listed_or_all),
|
||||
("mesh.planar", super::mesh::planar_body),
|
||||
("mesh.mirror", super::mirror::image_names),
|
||||
];
|
||||
|
||||
/// `body`, the imported `surface`, or every body of the open design.
|
||||
fn body_or_all(s: &Session, p: &Value) -> Result<Vec<String>> {
|
||||
match (p.get("body"), p.get("surface")) {
|
||||
(Some(b), None) => Ok(vec![b.as_str().ok_or_else(|| EngineError::param("body", crate::schema::ProblemKind::NotAName))?.to_string()]),
|
||||
(None, Some(_)) => Ok(vec![super::hex::surface(s, p)?.0]),
|
||||
(None, None) => design_bodies(s),
|
||||
_ => Err(EngineError::Params("give `body` or `surface`, not both".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// `bodies`, or every body of the open design.
|
||||
fn listed_or_all(s: &Session, p: &Value) -> Result<Vec<String>> {
|
||||
match p.get("bodies") {
|
||||
Some(_) => super::req(p, "bodies"),
|
||||
None => design_bodies(s),
|
||||
}
|
||||
}
|
||||
|
||||
fn design_bodies(s: &Session) -> Result<Vec<String>> {
|
||||
let design = s.design.as_deref().ok_or_else(|| EngineError::Params("open a design first".into()))?;
|
||||
Ok(design.bodies.iter().map(|b| b.name.clone()).collect())
|
||||
}
|
||||
|
||||
/// What running a meshing command would replace, for a confirmation before it runs.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Replacement {
|
||||
/// "CrankArm already has a mesh (7,274 hex20). Replace it?"
|
||||
pub question: String,
|
||||
/// What else goes with the old mesh: sets that list its labels, solved results.
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// What `command` with `params` would replace: `None` when it is not a mesher, its parameters
|
||||
/// do not name bodies, or none of its bodies has a mesh.
|
||||
pub fn replacement(s: &Session, command: &str, params: &Value) -> Option<Replacement> {
|
||||
let targets = MESHERS.iter().find(|(id, _)| *id == command)?.1;
|
||||
let bodies = targets(s, params).ok()?;
|
||||
let mut meshed = Vec::new();
|
||||
let mut removed = BodyMesh::default();
|
||||
for body in bodies.iter().collect::<BTreeSet<_>>() {
|
||||
let mesh = s.model.body_mesh(body);
|
||||
if mesh.elements.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let mut counts: BTreeMap<ElementKind, usize> = BTreeMap::new();
|
||||
for e in mesh.elements.iter().filter_map(|l| s.model.element(*l)) {
|
||||
*counts.entry(e.kind).or_default() += 1;
|
||||
}
|
||||
let kinds: Vec<String> = ElementKind::ALL.iter().filter_map(|k| counts.get(k).map(|n| format!("{} {}", thousands(*n), k.name()))).collect();
|
||||
meshed.push((body.as_str(), kinds.join(", ")));
|
||||
removed.elements.extend(mesh.elements);
|
||||
removed.nodes.extend(mesh.nodes);
|
||||
}
|
||||
let question = match meshed.as_slice() {
|
||||
[] => return None,
|
||||
[(body, counts)] => format!("{body} already has a mesh ({counts}). Replace it?"),
|
||||
many => {
|
||||
let list: Vec<String> = many.iter().map(|(body, counts)| format!("{body} ({counts})")).collect();
|
||||
format!("{} already have meshes. Replace them?", list.join(", "))
|
||||
}
|
||||
};
|
||||
let mut warnings = Vec::new();
|
||||
let stale = s.model.sets_using(&removed);
|
||||
if !stale.is_empty() {
|
||||
warnings.push(format!("Sets that list its nodes or elements by label ({}) will name labels of the old mesh.", stale.join(", ")));
|
||||
}
|
||||
let results: Vec<&str> = s.solved_steps().collect();
|
||||
if !results.is_empty() {
|
||||
warnings.push(format!("The results of {} will be cleared.", results.join(", ")));
|
||||
}
|
||||
Some(Replacement { question, warnings })
|
||||
}
|
||||
|
||||
/// `n` with thousands separators: 7274 → "7,274".
|
||||
fn thousands(n: usize) -> String {
|
||||
let digits = n.to_string();
|
||||
let mut out = String::with_capacity(digits.len() + digits.len() / 3);
|
||||
for (i, c) in digits.chars().enumerate() {
|
||||
if i > 0 && (digits.len() - i).is_multiple_of(3) {
|
||||
out.push(',');
|
||||
}
|
||||
out.push(c);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use fieldcraft_model::Element;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_mesher_is_a_command() {
|
||||
for (id, _) in MESHERS {
|
||||
assert!(crate::find_command(id).is_some(), "{id}");
|
||||
}
|
||||
assert_eq!(thousands(7274), "7,274");
|
||||
assert_eq!(thousands(999), "999");
|
||||
assert_eq!(thousands(1_000_000), "1,000,000");
|
||||
}
|
||||
|
||||
/// A 20 × 10 × 10 box split at x = 10 into `Box` (x < 10) and `Box (1)`.
|
||||
fn two_boxes() -> (crate::tests::TempDir, Session) {
|
||||
let commands = json!({"commands": [
|
||||
{"command": "solid.box", "params": {"length": 20, "width": 10, "height": 10, "body_name": "Box"}},
|
||||
{"command": "solid.split_body", "params": {"body": "Box", "plane": {"origin": [10, 0, 0], "normal": [1, 0, 0]}}},
|
||||
]});
|
||||
let bytes = fieldcraft_geometry::script_design(&commands.to_string()).unwrap();
|
||||
let (dir, path) = crate::tests::design_file(&bytes);
|
||||
let mut s = Session::default();
|
||||
s.execute("geometry.open", &json!({"path": path})).unwrap();
|
||||
(dir, s)
|
||||
}
|
||||
|
||||
/// A body's elements, by label.
|
||||
fn elements_of(s: &Session, body: &str) -> BTreeMap<u32, Element> {
|
||||
s.model.body_elements(body).into_iter().filter_map(|l| Some((l, s.model.element(l)?.clone()))).collect()
|
||||
}
|
||||
|
||||
/// Every mesher in [`MESHERS`], run twice on a body: the second run replaces the first (as
|
||||
/// many elements as a fresh mesh, reported as `replaced`), leaves the other body's mesh as it
|
||||
/// was, names the set that listed the old labels, and one undo brings the first mesh back.
|
||||
#[test]
|
||||
fn every_mesher_replaces_the_mesh_of_its_body_only() {
|
||||
let tet_other = json!({"command": "mesh.tet.generate", "params": {"body": "Box (1)", "size": 5}});
|
||||
let hex_box = json!({"command": "mesh.hex.generate", "params": {"body": "Box", "size": 2.5}});
|
||||
let square = json!([[0, 0], [10, 0], [10, 10], [0, 10]]);
|
||||
let cases: Vec<(&str, Vec<Value>, Value, &str, &str)> = vec![
|
||||
("mesh.tet.generate", vec![tet_other.clone()], json!({"body": "Box", "size": 4}), "Box", "Box (1)"),
|
||||
("mesh.hex.generate", vec![tet_other.clone()], json!({"body": "Box", "size": 2.5}), "Box", "Box (1)"),
|
||||
("mesh.hex.sweep", vec![tet_other.clone()], json!({"body": "Box", "size": 2.5}), "Box", "Box (1)"),
|
||||
("mesh.hex.mapped", vec![tet_other.clone()], json!({"body": "Box", "size": 2.5}), "Box", "Box (1)"),
|
||||
("mesh.hex.octree", vec![tet_other.clone()], json!({"body": "Box", "size": 2.5}), "Box", "Box (1)"),
|
||||
("mesh.hex.blocks", vec![tet_other.clone()], json!({"bodies": ["Box"], "size": 2.5}), "Box", "Box (1)"),
|
||||
("mesh.cells", vec![tet_other.clone()], json!({"bodies": ["Box"], "size": 2.5, "default": "hex"}), "Box", "Box (1)"),
|
||||
("mesh.planar", vec![tet_other.clone()], json!({"polygon": square, "size": 2.5, "name": "Box"}), "Box", "Box (1)"),
|
||||
// The image's tets (meshed before) are replaced by the mirrored hexahedra.
|
||||
(
|
||||
"mesh.mirror",
|
||||
vec![hex_box, tet_other],
|
||||
json!({"plane": {"point": [10, 0, 0], "normal": [1, 0, 0]}, "bodies": ["Box"]}),
|
||||
"Box (1)",
|
||||
"Box",
|
||||
),
|
||||
];
|
||||
let covered: BTreeSet<&str> = cases.iter().map(|c| c.0).collect();
|
||||
assert_eq!(covered, MESHERS.iter().map(|m| m.0).collect::<BTreeSet<_>>(), "every mesher has a case");
|
||||
|
||||
let (_dir, fresh) = two_boxes();
|
||||
for (id, prep, params, body, other) in cases {
|
||||
let mut s = fresh.clone();
|
||||
for c in &prep {
|
||||
s.execute(c["command"].as_str().unwrap(), &c["params"]).unwrap();
|
||||
}
|
||||
// What the session says it would replace matches what the command replaces.
|
||||
let first = s.execute(id, ¶ms).unwrap();
|
||||
let fresh_count = elements_of(&s, body).len();
|
||||
assert!(fresh_count > 0, "{id}: {first}");
|
||||
let others = elements_of(&s, other);
|
||||
assert!(!others.is_empty(), "{id}");
|
||||
let some: Vec<u32> = elements_of(&s, body).keys().take(3).copied().collect();
|
||||
s.execute("model.set.create", &json!({"name": "by_label", "elements": some})).unwrap();
|
||||
let asked = replacement(&s, id, ¶ms).unwrap_or_else(|| panic!("{id}: no question"));
|
||||
assert!(asked.question.starts_with(&format!("{body} already has a mesh (")), "{id}: {asked:?}");
|
||||
assert!(asked.warnings.iter().any(|w| w.contains("by_label")), "{id}: {asked:?}");
|
||||
|
||||
let before = s.model.clone();
|
||||
let second = s.execute(id, ¶ms).unwrap();
|
||||
assert_eq!(elements_of(&s, body).len(), fresh_count, "{id}: {second}");
|
||||
assert_eq!(elements_of(&s, other), others, "{id}: the other body's mesh is untouched");
|
||||
assert_eq!(
|
||||
second["replaced"],
|
||||
json!([{"body": body, "elements": fresh_count, "nodes": second["replaced"][0]["nodes"]}]),
|
||||
"{id}: {second}"
|
||||
);
|
||||
assert_eq!(second["stale_sets"], json!(["by_label"]), "{id}: {second}");
|
||||
// No node is left that no element uses.
|
||||
let used: BTreeSet<u32> = s.model.elements().values().flat_map(|e| e.nodes.iter().copied()).collect();
|
||||
assert!(s.model.nodes().keys().all(|n| used.contains(n)), "{id}: orphan nodes");
|
||||
|
||||
// A mesher is deterministic: the same mesh again is the same model, and no undo step.
|
||||
if s.model != before {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.model, before, "{id}: undo restores the first mesh");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tets_over_hexahedra_leave_only_tets() {
|
||||
let (_dir, mut s) = two_boxes();
|
||||
s.execute("mesh.hex.generate", &json!({"size": 2.5})).unwrap();
|
||||
let hexes = elements_of(&s, "Box").len();
|
||||
let other = elements_of(&s, "Box (1)");
|
||||
let r = s.execute("mesh.tet.generate", &json!({"body": "Box", "size": 4})).unwrap();
|
||||
assert_eq!(r["replaced"][0]["elements"], hexes, "{r}");
|
||||
assert!(elements_of(&s, "Box").values().all(|e| e.kind == ElementKind::Tet4));
|
||||
assert_eq!(elements_of(&s, "Box (1)"), other);
|
||||
let tets = s.model.clone();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(elements_of(&s, "Box").len(), hexes, "one undo brings the hexahedra back");
|
||||
assert!(elements_of(&s, "Box").values().all(|e| e.kind == ElementKind::Hex8));
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(s.model, tets);
|
||||
// Meshing every body replaces both.
|
||||
let r = s.execute("mesh.tet.generate", &json!({"size": 4})).unwrap();
|
||||
assert_eq!(r["replaced"].as_array().map(Vec::len), Some(2), "{r}");
|
||||
assert!(s.model.elements().values().all(|e| e.kind == ElementKind::Tet4));
|
||||
// A body without a mesh asks nothing.
|
||||
let (_dir2, s2) = two_boxes();
|
||||
assert_eq!(replacement(&s2, "mesh.tet.generate", &json!({"body": "Box"})), None);
|
||||
assert_eq!(replacement(&s, "mesh.block", &json!({"body": "Box"})), None, "not a mesher");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn results_solved_on_the_old_mesh_are_cleared_and_undo_brings_them_back() {
|
||||
let mut s = Session::default();
|
||||
let corners = json!([[0, 0, 0], [10, 0, 0], [10, 1, 0], [0, 1, 0], [0, 0, 1], [10, 0, 1], [10, 1, 1], [0, 1, 1]]);
|
||||
s.run_script(&json!([
|
||||
{"command": "mesh.block", "params": {"body": "Bar", "kind": "hex8", "corners": corners, "divisions": [10, 1, 1], "faces": {"6": "root", "4": "tip"}}},
|
||||
{"command": "model.set.create", "params": {"name": "all", "geometry": [{"body": "Bar"}]}},
|
||||
{"command": "model.set.create", "params": {"name": "root", "geometry": [{"body": "Bar", "face": "root"}]}},
|
||||
{"command": "model.set.create", "params": {"name": "tip", "geometry": [{"body": "Bar", "face": "tip"}]}},
|
||||
{"command": "model.material.create", "params": {"name": "Mat", "elastic": {"type": "isotropic", "young": 1000.0, "poisson": 0.0}}},
|
||||
{"command": "model.section.create", "params": {"name": "all", "set": "all", "material": "Mat", "kind": {"type": "solid"}}},
|
||||
{"command": "model.boundary_condition.create", "params": {"name": "Clamp", "type": "fixed", "target": {"set": "root"}}},
|
||||
{"command": "model.load.create", "params": {"name": "Pull", "type": "force", "target": {"set": "tip"}, "vector": [1, 0, 0]}},
|
||||
{"command": "model.step.create", "params": {"name": "Load", "procedure": {"type": "static"}, "boundary_conditions": ["Clamp"], "loads": ["Pull"]}}
|
||||
]))
|
||||
.unwrap();
|
||||
s.execute("solve.static", &json!({"step": "Load"})).unwrap();
|
||||
assert!(s.result("Load").is_some());
|
||||
let asked = replacement(&s, "mesh.planar", &json!({"polygon": [[0, 0], [10, 0], [10, 1], [0, 1]], "size": 1, "name": "Bar"})).unwrap();
|
||||
assert_eq!(asked.question, "Bar already has a mesh (10 hex8). Replace it?");
|
||||
assert!(asked.warnings.iter().any(|w| w.contains("results of Load")), "{asked:?}");
|
||||
let r = s.execute("mesh.planar", &json!({"polygon": [[0, 0], [10, 0], [10, 1], [0, 1]], "size": 1, "name": "Bar"})).unwrap();
|
||||
assert_eq!(r["results_cleared"], json!(["Load"]), "{r}");
|
||||
assert!(s.result("Load").is_none());
|
||||
assert!(s.model.elements().values().all(|e| e.kind.dimension() == 2));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.result("Load").is_some(), "undo brings the solved state back");
|
||||
}
|
||||
}
|
||||
@@ -2,9 +2,11 @@
|
||||
//! animation) and reaction sums. The display is session state ([`ResultsView`]): these
|
||||
//! commands are not edits, so they are not journalled or undone.
|
||||
|
||||
use crate::schema::ProblemKind;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{opt, xyz};
|
||||
use crate::requirement::Requirement;
|
||||
use crate::results::{Field, Kind, MAX_BANDS, MIN_BANDS, ResultsView};
|
||||
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
|
||||
|
||||
@@ -14,6 +16,7 @@ pub const DEFORMED: CommandSpec = CommandSpec {
|
||||
params: r#"{"step": "Load", "show": true, "scale": "auto"} — shows a solved step's deformed shape (`show: false` the undeformed mesh); `scale` is a factor (0 draws the undeformed shape, so a sequence from 0 swings it out) or "auto" (the largest displacement drawn a tenth of the model's size); `step` defaults to the step shown or the first solved one"#,
|
||||
form: Some(super::forms::DEFORMED),
|
||||
kind: CommandKind::Session,
|
||||
requires: &[Requirement::Result],
|
||||
run: deformed,
|
||||
};
|
||||
|
||||
@@ -23,6 +26,7 @@ pub const CONTOUR: CommandSpec = CommandSpec {
|
||||
params: r#"{"step": "Load", "field": "von_mises", "bands": 12} — contours of a nodal field: displacement, displacement_x/y/z, von_mises, max/mid/min_principal, stress_xx/yy/zz/xy/xz/yz (stresses for static steps), contact_pressure, contact_gap, contact_status (0 open, 1 closed or stick, 2 slip), contact_shear, contact_slip (friction; nonlinear static steps with contact, at the contacts' secondary surfaces); "none" turns them off; 2 to 24 bands"#,
|
||||
form: Some(super::forms::CONTOUR),
|
||||
kind: CommandKind::Session,
|
||||
requires: &[Requirement::Result],
|
||||
run: contour,
|
||||
};
|
||||
|
||||
@@ -32,6 +36,7 @@ pub const MODES: CommandSpec = CommandSpec {
|
||||
params: r#"{"step": "Modes", "mode": 1} — shows a mode shape of a solved frequency step (from 1) and lists every mode's frequency"#,
|
||||
form: Some(super::forms::MODES),
|
||||
kind: CommandKind::Session,
|
||||
requires: &[Requirement::Result],
|
||||
run: modes,
|
||||
};
|
||||
|
||||
@@ -41,6 +46,7 @@ pub const ANIMATE: CommandSpec = CommandSpec {
|
||||
params: r#"{"on": true} — animates the deformed shape: a mode swings through its positive and negative shape, a static step grows from undeformed to deformed"#,
|
||||
form: Some(super::forms::ANIMATE),
|
||||
kind: CommandKind::Session,
|
||||
requires: &[Requirement::Result],
|
||||
run: animate,
|
||||
};
|
||||
|
||||
@@ -50,6 +56,7 @@ pub const FRAME: CommandSpec = CommandSpec {
|
||||
params: r#"{"step": "Impact", "frame": 3, "time": 0.002} — shows a field frame of a solved explicit step, by index from 0 or the frame nearest a time (neither: the last), or of a nonlinear static step (one per converged increment, `time` its load factor; the deformed shape follows it, its contours show the final state); the deformed shape and contours follow it"#,
|
||||
form: Some(super::forms::FRAME),
|
||||
kind: CommandKind::Session,
|
||||
requires: &[Requirement::Result],
|
||||
run: frame,
|
||||
};
|
||||
|
||||
@@ -59,6 +66,7 @@ pub const REACTIONS: CommandSpec = CommandSpec {
|
||||
params: r#"{"step": "Load", "sets": ["root"], "about": [0, 0, 0]} — reaction force and moment (about the point) summed over each node set, and over the whole model; `sets` defaults to the sets the step's boundary conditions hold"#,
|
||||
form: Some(super::forms::REACTIONS),
|
||||
kind: CommandKind::Session,
|
||||
requires: &[Requirement::Result],
|
||||
run: reactions,
|
||||
};
|
||||
|
||||
@@ -68,6 +76,7 @@ pub const CLEAR: CommandSpec = CommandSpec {
|
||||
params: "{} — back to the model: hides the deformed shape, contours and modes",
|
||||
form: Some(&[]),
|
||||
kind: CommandKind::Session,
|
||||
requires: &[Requirement::ResultsShown],
|
||||
run: clear,
|
||||
};
|
||||
|
||||
@@ -165,7 +174,7 @@ fn deformed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn contour(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let step = step_for(s, p, Want::Any)?;
|
||||
let name = opt::<String>(p, "field")?.ok_or_else(|| EngineError::Params("`field` is required (a field id, or \"none\")".into()))?;
|
||||
let name = opt::<String>(p, "field")?.ok_or_else(|| EngineError::param("field", ProblemKind::Required))?;
|
||||
let field = match name.as_str() {
|
||||
"none" => None,
|
||||
id => Some(Field::parse(id).ok_or_else(|| {
|
||||
@@ -247,7 +256,7 @@ fn frame(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
(None, Some(t)) if t.is_finite() => {
|
||||
times.iter().enumerate().min_by(|a, b| (a.1 - t).abs().total_cmp(&(b.1 - t).abs())).map_or(last, |(i, _)| i)
|
||||
}
|
||||
(None, Some(_)) => return Err(EngineError::Params("`time` must be a number".into())),
|
||||
(None, Some(_)) => return Err(EngineError::param("time", ProblemKind::NotANumber)),
|
||||
(None, None) => last,
|
||||
};
|
||||
let v = view_of(s, &step)?;
|
||||
@@ -264,7 +273,7 @@ fn reactions(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let step = step_for(s, p, Want::Any)?;
|
||||
let about = if p.get("about").is_some() { xyz(p, "about")? } else { [0.0; 3] };
|
||||
if !about.iter().all(|c| c.is_finite()) {
|
||||
return Err(EngineError::Params("`about` must be a finite [x, y, z]".into()));
|
||||
return Err(EngineError::param("about", ProblemKind::NotAVector { len: 3 }));
|
||||
}
|
||||
let Some((result, current)) = s.latest_result(&step) else { return Err(EngineError::Params(solved_list(s))) };
|
||||
let Kind::Static(r) = result.kind() else {
|
||||
@@ -279,7 +288,7 @@ fn reactions(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.filter(|a| a.len() <= MAX_SETS)
|
||||
.ok_or_else(|| EngineError::Params(format!("`sets` must be a list of at most {MAX_SETS} set names")))?;
|
||||
list.iter()
|
||||
.map(|n| n.as_str().map(str::to_string).ok_or_else(|| EngineError::Params("`sets` must be set names".into())))
|
||||
.map(|n| n.as_str().map(str::to_string).ok_or_else(|| EngineError::param("sets", ProblemKind::NotNames)))
|
||||
.collect::<Result<_>>()?
|
||||
}
|
||||
None => {
|
||||
@@ -338,8 +347,8 @@ mod tests {
|
||||
fn the_display_follows_the_commands_and_is_not_an_edit() {
|
||||
let mut s = solved();
|
||||
let (journal, revision) = (s.journal.len(), s.revision());
|
||||
// Solving showed the first solved step.
|
||||
assert_eq!(s.results_view.as_ref().map(|v| (v.step.as_str(), v.contour)), Some(("Bend", Some(Field::VonMises))));
|
||||
// Solving showed the first solved step, a static one: contours on the undeformed shape.
|
||||
assert_eq!(s.results_view.as_ref().map(|v| (v.step.as_str(), v.contour, v.deformed)), Some(("Bend", Some(Field::VonMises), false)));
|
||||
s.execute("results.clear", &json!({})).unwrap();
|
||||
let r = s.execute("results.contour", &json!({"field": "von_mises"})).unwrap();
|
||||
assert_eq!(r["view"]["step"], "Bend", "{r}");
|
||||
@@ -356,7 +365,7 @@ mod tests {
|
||||
let r = s.execute("results.modes", &json!({"mode": 3})).unwrap();
|
||||
assert_eq!((r["view"]["step"].as_str(), r["view"]["mode"].as_u64()), (Some("Modes"), Some(3)));
|
||||
assert_eq!(r["modes"].as_array().map(Vec::len), Some(4));
|
||||
assert_eq!(s.results_view.as_ref().and_then(|v| v.contour), Some(Field::Displacement));
|
||||
assert_eq!(s.results_view.as_ref().map(|v| (v.contour, v.deformed)), Some((Some(Field::Displacement), true)), "a mode shape is deformed");
|
||||
assert!(s.execute("results.contour", &json!({"field": "von_mises"})).is_err());
|
||||
s.execute("results.contour", &json!({"field": "displacement", "bands": 6})).unwrap();
|
||||
s.execute("results.animate", &json!({})).unwrap();
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
//! Edge seeds: `mesh.seed.edge` sets a count or a size (with bias and constraint) on design
|
||||
//! edges, `mesh.seed.clear` removes seeds and `mesh.seed.list` lists them with the count each
|
||||
//! gives on its edge. Seeds live in the model (`fieldcraft_model::seeds`), are saved with it, and
|
||||
//! the meshers honour them.
|
||||
|
||||
use fieldcraft_geometry::{Design, Edge};
|
||||
use fieldcraft_model::{Bias, Divisions, Entity, GeometryRef, Seed, SeedConstraint};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::opt;
|
||||
use crate::requirement::Requirement;
|
||||
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
|
||||
|
||||
/// Most edges one command names.
|
||||
const MAX_EDGES: usize = 10_000;
|
||||
|
||||
pub const SEED_EDGE: CommandSpec = CommandSpec {
|
||||
id: "mesh.seed.edge",
|
||||
label: "Seed Edges",
|
||||
params: r#"{"edges": [{"body": "Body1", "edge": "F2:side:hi|F2:top"}, …], "count": 8 | "size": 2.5, "bias"?: {"ratio": 4, "toward": "start" | "end" | "both"}, "constraint"?: "exact" (default) | "min" | "free"} — seeds design edges (persistent edge names, geometry.bodies): `count` divisions, or `size` (the edge's length over it, rounded up). `bias` grades the elements geometrically, the largest `ratio` times the smallest, small at the edge's start, end or both ends. `constraint`: "exact" keeps the count (a mesher whose other edges cannot match refuses, naming the conflicting edges), "min" keeps at least it, "free" makes it a goal. Replaces a seed the edge had; an edge name without its `~k` number seeds every edge of that name. The hex meshers (sweep, mapped, blocks, cells) use the counts and spacing; the tet mesher uses the spacing on the edge and grades its size field from it"#,
|
||||
form: Some(super::forms::SEED_EDGE),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Design],
|
||||
run: seed_edge,
|
||||
};
|
||||
|
||||
pub const SEED_CLEAR: CommandSpec = CommandSpec {
|
||||
id: "mesh.seed.clear",
|
||||
label: "Clear Seeds",
|
||||
params: r#"{"edges"?: [{"body", "edge"}, …]} — removes the seeds on these edges (by the names they were seeded with), or every seed"#,
|
||||
form: Some(super::forms::SEED_CLEAR),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Seed],
|
||||
run: seed_clear,
|
||||
};
|
||||
|
||||
pub const SEED_LIST: CommandSpec = CommandSpec {
|
||||
id: "mesh.seed.list",
|
||||
label: "Seeds",
|
||||
params: "{} — the edge seeds, each with the edges of the open design it seeds, their lengths and the count it gives each (`stale`: the design has no such edge)",
|
||||
form: Some(&[]),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[],
|
||||
run: seed_list,
|
||||
};
|
||||
|
||||
/// The `edges` parameter: a list of edge references.
|
||||
fn edge_refs(p: &Value, required: bool) -> Result<Option<Vec<GeometryRef>>> {
|
||||
let refs: Option<Vec<GeometryRef>> = opt(p, "edges")?;
|
||||
let Some(refs) = refs else {
|
||||
return if required { Err(EngineError::Params("`edges` is required: a list of {body, edge}".into())) } else { Ok(None) };
|
||||
};
|
||||
if refs.is_empty() || refs.len() > MAX_EDGES {
|
||||
return Err(EngineError::Params(format!("`edges` must list 1 to {MAX_EDGES} edges")));
|
||||
}
|
||||
if let Some(r) = refs.iter().find(|r| !matches!(r.entity, Entity::Edge(_))) {
|
||||
return Err(EngineError::Params(format!("`edges` lists the {r}; name edges as {{body, edge}}")));
|
||||
}
|
||||
Ok(Some(refs))
|
||||
}
|
||||
|
||||
/// The edges of the design a reference selects (its `~k` pieces too).
|
||||
pub(crate) fn seeded_edges(design: &Design, r: &GeometryRef) -> Result<Vec<Edge>> {
|
||||
let Some(body) = design.body(&r.body) else { return Ok(Vec::new()) };
|
||||
Ok(body.edges()?.into_iter().filter(|e| GeometryRef::new(r.body.clone(), Entity::Edge(e.name.clone())).is_ok_and(|g| r.selects(&g))).collect())
|
||||
}
|
||||
|
||||
/// Every seed on the open design's edges, as the meshers take them. A mesher matches them to its
|
||||
/// own curves by position, so a seed on an edge two partition cells share holds in both.
|
||||
pub(crate) fn edge_seeds(s: &Session) -> Result<Vec<fieldcraft_mesh::seeds::EdgeSeed>> {
|
||||
let Some(design) = s.design.as_deref() else { return Ok(Vec::new()) };
|
||||
let mut out = Vec::new();
|
||||
// Each body's edges, found once.
|
||||
let mut edges: std::collections::BTreeMap<&str, (f64, Vec<Edge>)> = std::collections::BTreeMap::new();
|
||||
for seed in s.model.seeds() {
|
||||
let Some(body) = design.body(&seed.edge.body) else { continue };
|
||||
let (tolerance, all) = match edges.entry(body.name.as_str()) {
|
||||
std::collections::btree_map::Entry::Occupied(e) => e.into_mut(),
|
||||
std::collections::btree_map::Entry::Vacant(v) => {
|
||||
v.insert(((body.size()? * fieldcraft_geometry::EDGE_TOLERANCE).max(1e-4), body.edges()?))
|
||||
}
|
||||
};
|
||||
let selected = all.iter().filter(|e| GeometryRef::new(body.name.clone(), Entity::Edge(e.name.clone())).is_ok_and(|g| seed.edge.selects(&g)));
|
||||
for e in selected.cloned().collect::<Vec<_>>() {
|
||||
let tolerance = *tolerance;
|
||||
out.push(fieldcraft_mesh::seeds::EdgeSeed {
|
||||
name: format!("{}:{}", seed.edge.body, e.name),
|
||||
count: seed.count(e.length()) as usize,
|
||||
points: e.points,
|
||||
tolerance,
|
||||
bias: seed.bias,
|
||||
constraint: seed.constraint,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn design(s: &Session) -> Result<&Design> {
|
||||
s.design.as_deref().ok_or_else(|| EngineError::Params("open a design first (geometry.open)".into()))
|
||||
}
|
||||
|
||||
/// A seed's report: its definition and, per edge it seeds, the length and the count it gives.
|
||||
fn report(seed: &Seed, edges: &[Edge]) -> Value {
|
||||
let mut v = json!(seed);
|
||||
v["on"] = edges.iter().map(|e| json!({"edge": e.name, "length": e.length(), "count": seed.count(e.length())})).collect();
|
||||
v["stale"] = json!(edges.is_empty());
|
||||
v
|
||||
}
|
||||
|
||||
fn seed_edge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let refs = edge_refs(p, true)?.unwrap_or_default();
|
||||
let divisions = match (opt::<u32>(p, "count")?, opt::<f64>(p, "size")?) {
|
||||
(Some(n), None) => Divisions::Count(n),
|
||||
(None, Some(h)) => Divisions::Size(h),
|
||||
_ => return Err(EngineError::Params("give one of `count` (divisions) or `size` (element length)".into())),
|
||||
};
|
||||
let bias: Option<Bias> = opt(p, "bias")?;
|
||||
let constraint: SeedConstraint = opt(p, "constraint")?.unwrap_or_default();
|
||||
let design = design(s)?.clone();
|
||||
let mut out = Vec::with_capacity(refs.len());
|
||||
for r in refs {
|
||||
let edges = seeded_edges(&design, &r)?;
|
||||
if edges.is_empty() {
|
||||
return Err(EngineError::Params(format!("the design has no {r} (geometry.bodies lists the edges)")));
|
||||
}
|
||||
let seed = Seed::new(r, divisions, bias, constraint)?;
|
||||
out.push(report(&seed, &edges));
|
||||
s.model.set_seed(seed)?;
|
||||
}
|
||||
Ok(json!({"seeded": out.len(), "seeds": out}))
|
||||
}
|
||||
|
||||
fn seed_clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cleared = match edge_refs(p, false)? {
|
||||
None => s.model.clear_seeds(),
|
||||
Some(refs) => {
|
||||
if let Some(r) = refs.iter().find(|r| s.model.seed(r).is_none()) {
|
||||
return Err(EngineError::Params(format!("the {r} has no seed")));
|
||||
}
|
||||
refs.iter().filter(|r| s.model.remove_seed(r)).count()
|
||||
}
|
||||
};
|
||||
Ok(json!({"cleared": cleared, "left": s.model.seeds().len()}))
|
||||
}
|
||||
|
||||
fn seed_list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let mut out = Vec::with_capacity(s.model.seeds().len());
|
||||
for seed in s.model.seeds() {
|
||||
let edges = match s.design.as_deref() {
|
||||
Some(d) => seeded_edges(d, &seed.edge)?,
|
||||
None => Vec::new(),
|
||||
};
|
||||
out.push(report(seed, &edges));
|
||||
}
|
||||
Ok(Value::Array(out))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn plate() -> Session {
|
||||
super::super::datum::tests::plate().0
|
||||
}
|
||||
|
||||
fn thickness_edges(s: &mut Session) -> Vec<Value> {
|
||||
let bodies = s.execute("geometry.bodies", &json!({})).unwrap();
|
||||
bodies[0]["edges"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|e| (e["length"].as_f64().unwrap() - 10.0).abs() < 1e-6)
|
||||
.map(|e| json!({"body": "Body1", "edge": e["name"]}))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seeds_are_set_replaced_listed_cleared_and_undone() {
|
||||
let mut s = plate();
|
||||
let edges = thickness_edges(&mut s);
|
||||
let r = s.execute("mesh.seed.edge", &json!({"edges": edges[..2], "count": 4, "bias": {"ratio": 3, "toward": "end"}})).unwrap();
|
||||
assert_eq!(r["seeded"], 2);
|
||||
assert_eq!(r["seeds"][0]["on"][0]["count"], 4);
|
||||
assert_eq!(r["seeds"][0]["constraint"], "exact");
|
||||
// A size gives the length over it, rounded up; it replaces the count.
|
||||
let r = s.execute("mesh.seed.edge", &json!({"edges": [edges[0]], "size": 3.0, "constraint": "min"})).unwrap();
|
||||
assert_eq!(r["seeds"][0]["on"][0]["count"], 4);
|
||||
assert_eq!(s.model.seeds().len(), 2);
|
||||
let list = s.execute("mesh.seed.list", &json!({})).unwrap();
|
||||
assert_eq!(list.as_array().unwrap().len(), 2);
|
||||
assert!(list.as_array().unwrap().iter().all(|l| l["stale"] == false));
|
||||
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.model.seed(&serde_json::from_value(edges[0].clone()).unwrap()).unwrap().divisions, Divisions::Count(4));
|
||||
s.execute("mesh.seed.clear", &json!({"edges": [edges[1]]})).unwrap();
|
||||
assert_eq!(s.model.seeds().len(), 1);
|
||||
assert!(s.execute("mesh.seed.clear", &json!({"edges": [edges[1]]})).is_err());
|
||||
assert_eq!(s.execute("mesh.seed.clear", &json!({})).unwrap()["cleared"], 1);
|
||||
assert!(s.execute("mesh.seed.clear", &json!({})).is_err(), "nothing to clear");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seeds_survive_save_open_and_a_design_edit() {
|
||||
let (mut s, dir) = super::super::datum::tests::plate();
|
||||
let edges = thickness_edges(&mut s);
|
||||
s.execute("mesh.seed.edge", &json!({"edges": edges, "count": 5, "bias": {"ratio": 2, "toward": "both"}})).unwrap();
|
||||
let file = dir.join("seeded.fieldcraft");
|
||||
s.execute("file.save", &json!({"path": file.to_str().unwrap()})).unwrap();
|
||||
let mut back = Session::default();
|
||||
back.execute("file.open", &json!({"path": file.to_str().unwrap()})).unwrap();
|
||||
assert_eq!(back.model.seeds(), s.model.seeds());
|
||||
// The plate made thicker: the same edges, now 15 mm, keep their seeds.
|
||||
let design = dir.join("plate.solidcraft");
|
||||
let thick = fieldcraft_geometry::sample::Plate { thickness: 15.0, ..Default::default() };
|
||||
std::fs::write(&design, fieldcraft_geometry::sample::plate_design(&thick).unwrap()).unwrap();
|
||||
let r = back.execute("geometry.open", &json!({"path": design.to_str().unwrap()})).unwrap();
|
||||
assert_eq!(r["stale"]["seeds"], json!([]));
|
||||
let list = back.execute("mesh.seed.list", &json!({})).unwrap();
|
||||
for l in list.as_array().unwrap() {
|
||||
assert_eq!(l["on"].as_array().unwrap().len(), 1, "{l}");
|
||||
assert!((l["on"][0]["length"].as_f64().unwrap() - 15.0).abs() < 1e-6, "{l}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The polyline of edge `name` of body `body`.
|
||||
fn edge_points(s: &Session, body: &str, name: &str) -> Vec<[f64; 3]> {
|
||||
s.design.as_ref().unwrap().body(body).unwrap().edges().unwrap().into_iter().find(|e| e.name == name).unwrap().points
|
||||
}
|
||||
|
||||
/// The model's nodes on a straight edge, by their distance from its start, sorted.
|
||||
fn nodes_on(s: &Session, line: &[[f64; 3]]) -> Vec<f64> {
|
||||
let (a, b) = (line[0], *line.last().unwrap());
|
||||
let d = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
|
||||
let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
|
||||
let mut out: Vec<f64> = s
|
||||
.model
|
||||
.nodes()
|
||||
.values()
|
||||
.filter_map(|n| {
|
||||
let v = [n.xyz[0] - a[0], n.xyz[1] - a[1], n.xyz[2] - a[2]];
|
||||
let t = (v[0] * d[0] + v[1] * d[1] + v[2] * d[2]) / len;
|
||||
let off = [v[0] - t * d[0] / len, v[1] - t * d[1] / len, v[2] - t * d[2] / len];
|
||||
let off = (off[0] * off[0] + off[1] * off[1] + off[2] * off[2]).sqrt();
|
||||
(off < 1e-6 && (-1e-6..=len + 1e-6).contains(&t)).then_some(t)
|
||||
})
|
||||
.collect();
|
||||
out.sort_by(f64::total_cmp);
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_meshers_honour_seeds() {
|
||||
let mut s = plate();
|
||||
let edges = thickness_edges(&mut s);
|
||||
let name = edges[0]["edge"].as_str().unwrap().to_string();
|
||||
let line = edge_points(&s, "Body1", &name);
|
||||
let seed = json!({"edges": [edges[0]], "count": 5, "bias": {"ratio": 3, "toward": "end"}});
|
||||
s.execute("mesh.seed.edge", &seed).unwrap();
|
||||
// Hex sweep: five layers through the thickness, graded geometrically toward the edge's end.
|
||||
s.execute("mesh.hex.sweep", &json!({"body": "Body1", "size": 4})).unwrap();
|
||||
let t = nodes_on(&s, &line);
|
||||
let dt: Vec<f64> = t.windows(2).map(|w| w[1] - w[0]).collect();
|
||||
assert_eq!(dt.len(), 5, "{t:?}");
|
||||
assert!((dt[0] / dt[4] - 3.0).abs() < 1e-6, "{dt:?}");
|
||||
// Tet: the edge is divided at the seed's nodes.
|
||||
let r = s.execute("mesh.tet.generate", &json!({"body": "Body1", "size": 5})).unwrap();
|
||||
assert_eq!(r["bodies"][0]["seeds"][0]["mesh_edges"], 5, "{}", r["bodies"][0]["seeds"]);
|
||||
// Two exact seeds that cannot both hold are refused, naming both.
|
||||
s.execute("mesh.seed.edge", &json!({"edges": [edges[1]], "count": 3})).unwrap();
|
||||
let e = s.execute("mesh.hex.sweep", &json!({"body": "Body1", "size": 4})).unwrap_err().to_string();
|
||||
assert!(e.contains(&name) && e.contains(edges[1]["edge"].as_str().unwrap()) && e.contains("conflict"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_seed_on_a_cut_edge_holds_in_both_cells() {
|
||||
let (mut s, _dir) = super::super::datum::tests::plate();
|
||||
s.execute("geometry.datum", &json!({"name": "X30", "by": {"type": "offset", "plane": "yz", "offset": 30}})).unwrap();
|
||||
s.execute("geometry.partition", &json!({"name": "P", "datum": "X30"})).unwrap();
|
||||
// An edge of the cut face, 30 mm along y, on the cell with the hole.
|
||||
let edge = s
|
||||
.design
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.body("Body1/a")
|
||||
.unwrap()
|
||||
.edges()
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.find(|e| e.name.contains("partition:P:a") && (e.length() - 30.0).abs() < 1e-6)
|
||||
.unwrap();
|
||||
s.execute("mesh.seed.edge", &json!({"edges": [{"body": "Body1/a", "edge": edge.name}], "count": 9})).unwrap();
|
||||
let r = s.execute("mesh.cells", &json!({"default": "hex", "size": 2.5})).unwrap();
|
||||
assert_eq!(r["interfaces"][0]["joined"], "merged", "{r}");
|
||||
assert_eq!(nodes_on(&s, &edge.points).len(), 10, "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_seeds_are_refused_and_change_nothing() {
|
||||
let mut s = plate();
|
||||
let edges = thickness_edges(&mut s);
|
||||
let e = edges[0].clone();
|
||||
for p in [
|
||||
json!({}),
|
||||
json!({"edges": [], "count": 2}),
|
||||
json!({"edges": [e], "count": 2, "size": 1.0}),
|
||||
json!({"edges": [e]}),
|
||||
json!({"edges": [e], "count": 0}),
|
||||
json!({"edges": [e], "count": -3}),
|
||||
json!({"edges": [e], "count": 1e12}),
|
||||
json!({"edges": [e], "size": 0.0}),
|
||||
json!({"edges": [e], "count": 2, "bias": {"ratio": 1e9, "toward": "end"}}),
|
||||
json!({"edges": [e], "count": 2, "bias": {"ratio": 2, "toward": "middle"}}),
|
||||
json!({"edges": [e], "count": 2, "constraint": "loose"}),
|
||||
json!({"edges": [{"body": "Body1", "face": "x"}], "count": 2}),
|
||||
json!({"edges": [{"body": "Body1", "edge": "no|such"}], "count": 2}),
|
||||
json!({"edges": [{"body": "Nope", "edge": "a|b"}], "count": 2}),
|
||||
json!({"edges": "all", "count": 2}),
|
||||
] {
|
||||
assert!(s.execute("mesh.seed.edge", &p).is_err(), "{p}");
|
||||
}
|
||||
assert!(s.model.seeds().is_empty());
|
||||
assert!(s.journal.is_empty() || s.journal.iter().all(|(c, _)| c != "mesh.seed.edge"));
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! `solve.*`: run the model's steps with the implicit, the explicit or the lattice Boltzmann
|
||||
//! solver, keep the results in the session, and read them back.
|
||||
|
||||
use crate::schema::ProblemKind;
|
||||
use fieldcraft_explicit::{ExplicitResult, solve_explicit};
|
||||
use fieldcraft_lbm::{FluidResult, Obstacle};
|
||||
use fieldcraft_mesh::surface::{BoundarySurface, SurfaceOptions};
|
||||
@@ -13,6 +14,7 @@ use fieldcraft_solver::{
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{labels, opt, points, req};
|
||||
use crate::requirement::Requirement;
|
||||
use crate::{CommandKind, CommandSpec, EngineError, Result, Session, StepResult};
|
||||
|
||||
pub const RUN: CommandSpec = CommandSpec {
|
||||
@@ -21,6 +23,7 @@ pub const RUN: CommandSpec = CommandSpec {
|
||||
params: r#"{} — solves every step in order with its procedure's solver (solve.static, solve.frequency, solve.explicit, solve.fluid with their default caps) and keeps the results; stops at the first step that fails, naming it"#,
|
||||
form: Some(&[]),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Analysable, Requirement::ElementMaterial, Requirement::ElementSection, Requirement::Step],
|
||||
run: run_all,
|
||||
};
|
||||
|
||||
@@ -30,6 +33,7 @@ pub const STATIC: CommandSpec = CommandSpec {
|
||||
params: r#"{"step": "Load", "max_dofs": 6000000, "max_factor_entries": 400000000, "threads": 8} — solves a linear static or coupled temperature–displacement step (the only one when `step` is left out) and keeps the result in the session; the caps may only be lowered; `threads` (1 to 256, by default the session's: `FIELDCRAFT_THREADS` or the cores) changes only the time, never the result"#,
|
||||
form: Some(super::forms::SOLVE_STATIC),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Analysable, Requirement::ElementMaterial, Requirement::ElementSection, Requirement::Step],
|
||||
run: run_static,
|
||||
};
|
||||
|
||||
@@ -39,6 +43,7 @@ pub const NONLINEAR: CommandSpec = CommandSpec {
|
||||
params: r#"{"step": "Inflate", "max_dofs": 6000000, "max_factor_entries": 400000000, "max_newton_iterations": 100000, "threads": 8} — solves a nonlinear static step (the only one when `step` is left out) in load increments with Newton–Raphson iterations and keeps the result in the session: the final displacements, reactions, Cauchy stresses and logarithmic strains (small strains without nonlinear geometry), the equivalent plastic strain of plastic materials (the largest in the summary), every increment's load factor, iterations and residuals (force, displacement and energy, relative to their tolerances' scales), and a displacement frame per converged increment, and with contact pairs (interaction.contact.pair: mortar contact by augmented Lagrangian, Coulomb friction by a return map) each contact's force, normal force, largest pressure, closed and slipping nodes, deepest penetration and augmentations (solve.probe gives each secondary node's pressure, gap and status, and with friction its shear traction and slip); the caps may only be lowered (`max_newton_iterations` over the whole step); `threads` as for solve.static"#,
|
||||
form: Some(super::forms::SOLVE_NONLINEAR),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Analysable, Requirement::ElementMaterial, Requirement::ElementSection, Requirement::Step],
|
||||
run: run_nonlinear,
|
||||
};
|
||||
|
||||
@@ -48,6 +53,7 @@ pub const HEAT: CommandSpec = CommandSpec {
|
||||
params: r#"{"step": "Heat", "max_dofs": 6000000, "max_factor_entries": 400000000, "threads": 8} — steady or transient heat conduction of a heat transfer step (the only one when `step` is left out): temperatures, heat flux and the heat flow at prescribed temperatures, kept in the session; the caps may only be lowered; `threads` as for solve.static"#,
|
||||
form: Some(super::forms::SOLVE_STATIC),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Analysable, Requirement::ElementMaterial, Requirement::ElementSection, Requirement::Step],
|
||||
run: run_heat,
|
||||
};
|
||||
|
||||
@@ -57,6 +63,7 @@ pub const FREQUENCY: CommandSpec = CommandSpec {
|
||||
params: r#"{"step": "Modes", "mass": "consistent|lumped", "shift": 0.0, "max_dofs": 6000000, "max_factor_entries": 400000000, "max_iterations": 3000, "threads": 8} — natural frequencies and mode shapes of a frequency step (its modes and range); `max_iterations` caps the Lanczos vectors; the result stays in the session; `threads` as for solve.static"#,
|
||||
form: Some(super::forms::SOLVE_FREQUENCY),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Analysable, Requirement::ElementMaterial, Requirement::ElementSection, Requirement::Step],
|
||||
run: run_frequency,
|
||||
};
|
||||
|
||||
@@ -66,6 +73,7 @@ pub const BUCKLE: CommandSpec = CommandSpec {
|
||||
params: r#"{"step": "Buckle", "max_dofs": 6000000, "max_factor_entries": 400000000, "max_iterations": 3000, "threads": 8} — linear buckling of a buckling step (the only one when `step` is left out): the step's loads as a linear preload, then the lowest load factors λ with (K + λ K_σ) φ = 0 and their mode shapes (largest component 1), or those above the step's shift (whose LDLᵀ factor counts the load factors below it); negative load factors found are reported; the result stays in the session and its modes display like frequency modes; `threads` as for solve.static"#,
|
||||
form: Some(super::forms::SOLVE_BUCKLE),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Analysable, Requirement::ElementMaterial, Requirement::ElementSection, Requirement::Step],
|
||||
run: run_buckle,
|
||||
};
|
||||
|
||||
@@ -75,6 +83,7 @@ pub const EXPLICIT: CommandSpec = CommandSpec {
|
||||
params: r#"{"step": "Impact", "max_dofs": 6000000, "max_increments": 1000000000, "max_output_values": 50000000, "max_contact_faces": 10000000, "threads": 8} — transient response of an explicit dynamic step (the only one when `step` is left out) by central differences, with the model's contacts (interaction.contact.*) and the step's rigid walls; keeps its histories and field frames in the session and reports each contact's peak force, first and last contact, deepest penetration, friction dissipated and the nodes adjusted at the start; the caps may only be lowered (the step's own increment cap applies too); `threads` as for solve.static"#,
|
||||
form: Some(super::forms::SOLVE_EXPLICIT),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Analysable, Requirement::ElementMaterial, Requirement::ElementSection, Requirement::Step],
|
||||
run: run_explicit,
|
||||
};
|
||||
|
||||
@@ -84,6 +93,7 @@ pub const HISTORY: CommandSpec = CommandSpec {
|
||||
params: r#"{"step": "Impact", "every": 1} — the time histories of a solved explicit step: time, increment, energies, momentum, constraint force, the normal force across each contact (in `contacts` order) and the history nodes' displacement and velocity; `every` keeps one sample in so many (by default enough to return at most 10000)"#,
|
||||
form: Some(super::forms::SOLVE_HISTORY),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Result],
|
||||
run: history,
|
||||
};
|
||||
|
||||
@@ -93,6 +103,7 @@ pub const FLUID: CommandSpec = CommandSpec {
|
||||
params: r#"{"step": "Flow", "max_cells": 16000000, "max_steps": 10000000, "max_cell_updates": 1e12, "max_frame_bytes": 2e9, "threads": 8} — runs a fluid step with the lattice Boltzmann solver (the only fluid step when `step` is left out): obstacles are triangulated from the open design or taken from imported surfaces; returns the time step, relaxation time, Mach number, mass and the final force on every wall; the caps may only be lowered; `threads` as for solve.static"#,
|
||||
form: Some(super::forms::SOLVE_FLUID),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::FluidDomain, Requirement::Step],
|
||||
run: run_fluid,
|
||||
};
|
||||
|
||||
@@ -102,6 +113,7 @@ pub const PROBE: CommandSpec = CommandSpec {
|
||||
params: r#"{"step": "Load", "nodes": [1, 2] (or "set": "fillet", a set's nodes), "mode": 1, "frame": 0} — the stored result at nodes (with `max_von_mises`, the largest among them, for static steps): displacement, rotation, reaction, reaction moment, stress and von Mises (static, with `elements` each element's results: solid, 2D and truss nodal stresses (and, in a nonlinear step, the equivalent plastic strain at the integration points of a plastic element), shell section forces (N, M, Q per length in the element's axes) and bottom, middle and top stresses, beam end forces (N, V_y, V_z, T, M_y, M_z in its axes)), the shape of mode `mode` with its rotations (frequency, from 1), or displacement and velocity in field frame `frame` (explicit, from 0; the last by default) at `nodes` (or at the nodes nearest to points: "at": [[x, y, z], ...], lowest label on a tie, each entry then giving its `xyz` and `distance`) and, with `elements` (explicit), each element's stress, von Mises stress, strain, equivalent plastic strain, damage, temperature and whether it has eroded; a coupled reference point's label gives its six displacements (translations, rotations) and reactions (forces, moments). Fluid steps: {"step": "Flow", "points": [[x, y, z]], "frame": 10 (default the last)} gives velocity and pressure in the cells at the points; {"step": "Flow", "forces": ["x_min", "F2:top", "Body1/F2:top"]} gives those walls' force histories"#,
|
||||
form: Some(super::forms::SOLVE_PROBE),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Result],
|
||||
run: probe,
|
||||
};
|
||||
|
||||
@@ -123,7 +135,7 @@ fn cap<T: Copy + TryInto<u64> + TryFrom<u64> + std::fmt::Display>(p: &Value, key
|
||||
.as_u64()
|
||||
.filter(|n| (1..=most).contains(n))
|
||||
.and_then(|n| T::try_from(n).ok())
|
||||
.ok_or_else(|| EngineError::Params(format!("`{key}` must be a whole number from 1 to {default}"))),
|
||||
.ok_or_else(|| EngineError::param(key, ProblemKind::NotAWholeNumber { min: 1, max: i64::try_from(most).unwrap_or(i64::MAX) })),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -379,7 +391,7 @@ fn history(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let h = &r.history;
|
||||
let samples = h.time.len();
|
||||
let every = match opt::<u64>(p, "every")? {
|
||||
Some(0) => return Err(EngineError::Params("`every` must be at least 1".into())),
|
||||
Some(0) => return Err(EngineError::param("every", ProblemKind::Below(1.0))),
|
||||
Some(k) => usize::try_from(k).unwrap_or(usize::MAX),
|
||||
None => samples.div_ceil(MAX_HISTORY_SAMPLES).max(1),
|
||||
};
|
||||
@@ -530,7 +542,7 @@ fn probe_fluid(r: &FluidResult, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn probe(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let step = opt::<String>(p, "step")?.ok_or_else(|| EngineError::Params("`step` is required".into()))?;
|
||||
let step = opt::<String>(p, "step")?.ok_or_else(|| EngineError::param("step", ProblemKind::Required))?;
|
||||
let result = s.result(&step).ok_or_else(|| {
|
||||
EngineError::Params(if s.latest_result(&step).is_some() {
|
||||
format!("the result of step `{step}` is stale (the model changed since it was solved); solve it again")
|
||||
@@ -792,7 +804,7 @@ pub(crate) mod tests {
|
||||
s.execute("solve.run", &json!({})).unwrap();
|
||||
assert!(s.result("Impact").is_some());
|
||||
let mut empty = Session::default();
|
||||
assert!(empty.execute("solve.run", &json!({})).unwrap_err().to_string().contains("no steps"));
|
||||
assert!(empty.execute("solve.run", &json!({})).unwrap_err().to_string().contains("Needs a mesh"));
|
||||
}
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
//! `model.boundary_condition.symmetry`: a symmetry condition on a datum plane, so half of a
|
||||
//! symmetric part can be solved as a half.
|
||||
//!
|
||||
//! The condition holds the displacement normal to the plane, and the rotations about the two
|
||||
//! axes in it, at zero (`type: "symmetry"`). Its set is given, or made of the faces of the open
|
||||
//! design's bodies that lie on the plane (the cut faces of a partition by that datum, `partition:
|
||||
//! <name>:a|b`), so it follows the geometry through a remesh.
|
||||
|
||||
use fieldcraft_geometry::FaceSurface;
|
||||
use fieldcraft_model::{BoundaryCondition, GeometryRef, Set, Symmetry, Target};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::requirement::Requirement;
|
||||
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
|
||||
|
||||
pub const SYMMETRY: CommandSpec = CommandSpec {
|
||||
id: "model.boundary_condition.symmetry",
|
||||
label: "Symmetry Plane",
|
||||
params: r#"{"name": "Sym", "datum": "Mid" (a datum plane normal to X, Y or Z), "set"?: "cut" (default: a new set of the same name holding every face of the open design's bodies on the plane, e.g. a partition's cut faces), "bodies"?: ["Part/a"] (only their faces)} — a symmetry boundary condition on the plane: zero displacement normal to it and zero rotation about the axes in it, so half a symmetric part (loaded symmetrically, with half the load) is solved as a half. Add it to the steps (model.step.activate). Planes not normal to X, Y or Z are not supported yet"#,
|
||||
form: Some(super::forms::SYMMETRY),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::DatumPlane],
|
||||
run: symmetry,
|
||||
};
|
||||
|
||||
/// A face lies on the plane within this fraction of its body's size.
|
||||
const ON_PLANE: f64 = 1e-6;
|
||||
|
||||
fn symmetry(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = super::name(p)?.to_string();
|
||||
let datum: String = super::req(p, "datum")?;
|
||||
let (point, normal) = s
|
||||
.model
|
||||
.datum(&datum)
|
||||
.and_then(|d| d.plane())
|
||||
.ok_or_else(|| EngineError::Params(format!("no datum plane `{}`", datum.chars().take(64).collect::<String>())))?;
|
||||
let axis = (0..3).find(|&k| (normal[k].abs() - 1.0).abs() < 1e-9).ok_or_else(|| {
|
||||
EngineError::Params(format!("not supported yet: symmetry about a plane not normal to X, Y or Z (datum `{datum}` has normal {normal:?})"))
|
||||
})?;
|
||||
let plane = [Symmetry::X, Symmetry::Y, Symmetry::Z][axis];
|
||||
let set = match p.get("set") {
|
||||
Some(_) => super::req::<String>(p, "set")?,
|
||||
None => {
|
||||
let only: Option<Vec<String>> = super::opt(p, "bodies")?;
|
||||
let design =
|
||||
s.design.as_deref().ok_or_else(|| EngineError::Params("open a design to find the faces on the plane, or give `set`".into()))?;
|
||||
let mut faces = Vec::new();
|
||||
for b in &design.bodies {
|
||||
if only.as_ref().is_some_and(|o| !o.contains(&b.name)) {
|
||||
continue;
|
||||
}
|
||||
let tol = ON_PLANE * b.size()?.max(1.0);
|
||||
for (f, surface) in b.faces().iter().zip(b.face_surfaces()?) {
|
||||
if let Some(FaceSurface::Plane { normal: m, point: q }) = surface {
|
||||
let parallel = (m[axis].abs() - 1.0).abs() < 1e-9;
|
||||
if parallel && (q[axis] - point[axis]).abs() < tol {
|
||||
faces.push(GeometryRef::face(b.name.as_str(), f.name.as_str())?);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if faces.is_empty() {
|
||||
return Err(EngineError::Params(format!("no face of the design lies on datum `{datum}`: partition by it first, or give `set`")));
|
||||
}
|
||||
s.model.add_set(&name, Set::of_geometry(faces))?;
|
||||
name.clone()
|
||||
}
|
||||
};
|
||||
s.model.add_boundary_condition(&name, BoundaryCondition::Symmetry { target: Target::Set(set.clone()), plane })?;
|
||||
let faces = s.model.set(&set).map_or(0, |x| x.geometry.len());
|
||||
let axis_name = ["x", "y", "z"].get(axis).copied().unwrap_or("x");
|
||||
Ok(json!({"name": name, "set": set, "plane": axis_name, "faces": faces}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A 40 × 10 × 10 bar along x (0..40, 0..10, 0..10), the datum `Mid` at y = 5.
|
||||
fn bar(half: bool) -> (crate::tests::TempDir, Session) {
|
||||
let commands = json!({"commands": [
|
||||
{"command": "solid.box", "params": {"length": 40, "width": 10, "height": 10, "body_name": "Bar"}},
|
||||
]});
|
||||
let bytes = fieldcraft_geometry::script_design(&commands.to_string()).unwrap();
|
||||
let (dir, path) = crate::tests::design_file(&bytes);
|
||||
let mut s = Session::default();
|
||||
s.execute("geometry.open", &json!({"path": path})).unwrap();
|
||||
s.execute("geometry.datum", &json!({"name": "Mid", "by": {"type": "offset", "plane": "zx", "offset": 5}})).unwrap();
|
||||
if half {
|
||||
s.execute("geometry.partition", &json!({"name": "Half", "datum": "Mid"})).unwrap();
|
||||
}
|
||||
(dir, s)
|
||||
}
|
||||
|
||||
fn face(s: &Session, body: &str, point: [f64; 3]) -> String {
|
||||
let shape = s.design.as_ref().unwrap().body(body).unwrap();
|
||||
let f = shape.nearest_faces(&[point], 0.01).unwrap()[0].unwrap();
|
||||
shape.faces()[f as usize].name.clone()
|
||||
}
|
||||
|
||||
/// Clamp the x = 0 end and push the x = 40 end down (−z) with `force`, solve, and give the
|
||||
/// largest downward tip deflection and the clamp's reaction.
|
||||
fn bend(s: &mut Session, body: &str, force: f64, extra: &[&str]) -> (f64, f64) {
|
||||
let (root, tip) = (face(s, body, [0.0, 2.5, 5.0]), face(s, body, [40.0, 2.5, 5.0]));
|
||||
let mut bcs = vec!["Clamp".to_string()];
|
||||
bcs.extend(extra.iter().map(|x| x.to_string()));
|
||||
let script = json!([
|
||||
{"command": "model.set.create", "params": {"name": "all", "geometry": [{"body": body}]}},
|
||||
{"command": "model.set.create", "params": {"name": "root", "geometry": [{"body": body, "face": root}]}},
|
||||
{"command": "model.set.create", "params": {"name": "tip", "geometry": [{"body": body, "face": tip}]}},
|
||||
{"command": "model.material.create", "params": {"name": "Steel", "elastic": {"type": "isotropic", "young": 210000, "poisson": 0.3}}},
|
||||
{"command": "model.section.create", "params": {"name": "Bar", "set": "all", "material": "Steel", "kind": {"type": "solid"}}},
|
||||
{"command": "model.boundary_condition.create", "params": {"name": "Clamp", "type": "fixed", "target": {"set": "root"}}},
|
||||
{"command": "model.load.create", "params": {"name": "Push", "type": "force", "target": {"set": "tip"}, "vector": [0, 0, -force]}},
|
||||
{"command": "model.step.create", "params": {"name": "Load", "procedure": {"type": "static"}, "boundary_conditions": bcs, "loads": ["Push"]}},
|
||||
]);
|
||||
s.run_script(&script).unwrap();
|
||||
s.execute("solve.static", &json!({})).unwrap();
|
||||
let tip = s.model.resolve_set("tip").unwrap().nodes;
|
||||
let probe = s.execute("solve.probe", &json!({"step": "Load", "nodes": tip})).unwrap();
|
||||
let w = probe["nodes"].as_array().unwrap().iter().map(|n| -n["displacement"][2].as_f64().unwrap()).fold(f64::MIN, f64::max);
|
||||
let r = s.execute("results.reactions", &json!({"step": "Load", "sets": ["root"]})).unwrap();
|
||||
(w, r["sets"][0]["force"][2].as_f64().unwrap_or(f64::NAN))
|
||||
}
|
||||
|
||||
/// Half the bar, cut on its symmetry plane y = 5, with the symmetry condition and half the
|
||||
/// load, bends as the whole bar does: the same deflection, half the reaction.
|
||||
#[test]
|
||||
fn a_half_model_with_symmetry_matches_the_whole() {
|
||||
let (_d1, mut whole) = bar(false);
|
||||
whole.execute("mesh.hex.mapped", &json!({"body": "Bar", "size": 2.5, "order": 2})).unwrap();
|
||||
let full = bend(&mut whole, "Bar", 1000.0, &[]);
|
||||
|
||||
let (_d2, mut half) = bar(true);
|
||||
half.execute("mesh.hex.mapped", &json!({"body": "Bar/a", "size": 2.5, "order": 2})).unwrap();
|
||||
let r = half.execute("model.boundary_condition.symmetry", &json!({"name": "Sym", "datum": "Mid", "bodies": ["Bar/a"]})).unwrap();
|
||||
assert_eq!(r, json!({"name": "Sym", "set": "Sym", "plane": "y", "faces": 1}));
|
||||
assert_eq!(half.model.set("Sym").unwrap().geometry[0].entity, fieldcraft_model::geometry::Entity::Face("partition:Half:a".into()));
|
||||
let halved = bend(&mut half, "Bar/a", 500.0, &["Sym"]);
|
||||
assert!((halved.0 - full.0).abs() < 1e-9 * full.0, "deflection {} vs {}", halved.0, full.0);
|
||||
assert!((2.0 * halved.1 - full.1).abs() < 1e-9 * full.1.abs(), "reaction {} vs {}", halved.1, full.1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inclined_planes_and_hostile_params_change_nothing() {
|
||||
let (_d, mut s) = bar(true);
|
||||
s.execute("geometry.datum", &json!({"name": "Tilt", "by": {"type": "point_normal", "point": [0, 0, 0], "normal": [1, 1, 0]}})).unwrap();
|
||||
s.execute("geometry.datum", &json!({"name": "Out", "by": {"type": "offset", "plane": "xy", "offset": 100}})).unwrap();
|
||||
s.execute("geometry.datum.axis", &json!({"name": "Ax", "by": {"type": "principal", "axis": "x"}})).unwrap();
|
||||
let model = s.model.clone();
|
||||
let e = s.execute("model.boundary_condition.symmetry", &json!({"name": "S", "datum": "Tilt"})).unwrap_err();
|
||||
assert!(e.to_string().contains("not supported yet"), "{e}");
|
||||
for p in [
|
||||
json!({"name": "S", "datum": "Out"}),
|
||||
json!({"name": "S", "datum": "Ax"}),
|
||||
json!({"name": "S", "datum": "Nope"}),
|
||||
json!({"name": "S", "datum": "Mid", "set": "nope"}),
|
||||
json!({"name": "S", "datum": "Mid", "bodies": ["Nope"]}),
|
||||
json!({"name": "1S", "datum": "Mid"}),
|
||||
json!({"datum": "Mid"}),
|
||||
] {
|
||||
assert!(s.execute("model.boundary_condition.symmetry", &p).is_err(), "{p}");
|
||||
}
|
||||
assert_eq!(s.model, model);
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
//! Geometry tags on the mesh: which body, face, edge or vertex each mesh entity lies on. Meshers
|
||||
//! write them; these commands set them by hand (for a mesh from elsewhere) and clear them.
|
||||
|
||||
use crate::schema::ProblemKind;
|
||||
use fieldcraft_model::{ElementFace, GeometryRef, MAX_ELEMENTS};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{opt, req};
|
||||
use crate::requirement::Requirement;
|
||||
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
|
||||
|
||||
pub const TAG: CommandSpec = CommandSpec {
|
||||
@@ -13,11 +15,19 @@ pub const TAG: CommandSpec = CommandSpec {
|
||||
params: r#"{"geometry": {"body": "Body1"} | {"body", "face"} | {"body", "edge"} | {"body", "vertex"}, "elements": [labels] (filling a body, face or edge), "faces": [{"element": 1, "face": 3}] (on a face), "edges": [{"element": 1, "edge": 2}] (on an edge), "nodes": [labels] (on a vertex)} — records where the mesh lies on the geometry, so sets named by geometry resolve"#,
|
||||
form: Some(super::forms::TAG),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Mesh],
|
||||
run: tag,
|
||||
};
|
||||
|
||||
pub const TAG_CLEAR: CommandSpec =
|
||||
CommandSpec { id: "mesh.tag.clear", label: "Clear Geometry Tags", params: "{}", form: Some(&[]), kind: CommandKind::Model, run: tag_clear };
|
||||
pub const TAG_CLEAR: CommandSpec = CommandSpec {
|
||||
id: "mesh.tag.clear",
|
||||
label: "Clear Geometry Tags",
|
||||
params: "{}",
|
||||
form: Some(&[]),
|
||||
kind: CommandKind::Model,
|
||||
requires: &[Requirement::Mesh],
|
||||
run: tag_clear,
|
||||
};
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
@@ -29,7 +39,7 @@ struct ElementEdge {
|
||||
/// An optional list parameter of at most [`MAX_ELEMENTS`] entries.
|
||||
fn list<'a, T: serde::Deserialize<'a>>(p: &'a Value, key: &str) -> Result<Vec<T>> {
|
||||
if p.get(key).and_then(Value::as_array).is_some_and(|a| a.len() > MAX_ELEMENTS) {
|
||||
return Err(EngineError::Params(format!("`{key}` must be a list of at most {MAX_ELEMENTS} entries")));
|
||||
return Err(EngineError::param(key, ProblemKind::NotAList { max: MAX_ELEMENTS, what: "entries" }));
|
||||
}
|
||||
Ok(opt(p, key)?.unwrap_or_default())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
//! `app.update.check`: is a newer FieldCraft published? The same check as the desktop app's
|
||||
//! Help › Check for Updates and `fieldcraft-cli update --check` (docs/updates.md). It only
|
||||
//! reports: nothing is downloaded or installed, and no dialog opens.
|
||||
//!
|
||||
//! Checking reaches the network, so it is switched on only by the programs that may
|
||||
//! ([`enable_checks`]: the desktop app and the CLI); everywhere else (tests, scratch sessions,
|
||||
//! the browser) the command refuses without asking anything.
|
||||
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
|
||||
|
||||
pub const CHECK: CommandSpec = CommandSpec {
|
||||
id: "app.update.check",
|
||||
label: "Check for Updates",
|
||||
params: r#"{} — asks GitHub Releases for the latest published FieldCraft release and compares it with this version: current, latest, newer, url (its page and release notes), published, signed (whether it can be verified and installed from the app) and asset (the file this install would download; null when it cannot update itself). Reports only: nothing is downloaded or installed. Desktop app and fieldcraft-cli only"#,
|
||||
form: Some(&[]),
|
||||
kind: CommandKind::Session,
|
||||
requires: &[],
|
||||
run: check,
|
||||
};
|
||||
|
||||
static ENABLED: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// Let `app.update.check` reach the release server (the desktop app and the CLI do).
|
||||
pub fn enable_checks(on: bool) {
|
||||
ENABLED.store(on, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn check(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
Err(EngineError::Params("not in the browser: the web app offers Reload to update when a new version is deployed".into()))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn check(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
if !ENABLED.load(Ordering::SeqCst) {
|
||||
return Err(EngineError::Params("update checks are off in this session (the desktop app and fieldcraft-cli check for updates)".into()));
|
||||
}
|
||||
let check = fieldcraft_update::net::Client::from_env().check().map_err(|e| EngineError::Params(e.to_string()))?;
|
||||
let asset = fieldcraft_update::install::here().asset_name(&check.latest.version, std::env::consts::ARCH);
|
||||
Ok(check.to_json(asset.as_deref()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Off unless a program switches it on: tests and scratch sessions never reach the network.
|
||||
#[test]
|
||||
fn checks_are_off_unless_enabled() {
|
||||
let e = Session::default().execute("app.update.check", &json!({})).unwrap_err();
|
||||
assert!(e.to_string().contains("update checks are off"), "{e}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
//! What the viewport hides: `view.hide`, `view.show`, `view.isolate` and `view.show_all`.
|
||||
//!
|
||||
//! The hidden items (bodies, imported surfaces, datums, boundary conditions, loads, reference
|
||||
//! points, couplings) are view state ([`fieldcraft_io::View`]): saved with the model and marking
|
||||
//! it unsaved, but not a definition, so they are neither journalled nor undone and they leave
|
||||
//! results current. A hidden item is not drawn, so it cannot be picked either. An item that goes
|
||||
//! away (deleted, or a body cut into cells) is forgotten.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use fieldcraft_io::{Item, ItemKind, MAX_HIDDEN};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
|
||||
|
||||
pub const HIDE: CommandSpec = CommandSpec {
|
||||
id: "view.hide",
|
||||
label: "Hide",
|
||||
params: concat!(
|
||||
r#"{"items": [{"kind": "body" | "surface" | "datum" | "boundary_condition" | "load" | "reference_point" | "coupling", "name": "Sym"}]}"#,
|
||||
" — hides the items in the viewport (and from picking); view state, saved with the model"
|
||||
),
|
||||
form: Some(super::forms::VIEW_ITEMS),
|
||||
kind: CommandKind::Session,
|
||||
requires: &[],
|
||||
run: |s, p| change(s, p, Change::Hide),
|
||||
};
|
||||
|
||||
pub const SHOW: CommandSpec = CommandSpec {
|
||||
id: "view.show",
|
||||
label: "Show",
|
||||
params: concat!(
|
||||
r#"{"items": [{"kind": "body" | "surface" | "datum" | "boundary_condition" | "load" | "reference_point" | "coupling", "name": "Sym"}]}"#,
|
||||
" — shows hidden items again"
|
||||
),
|
||||
form: Some(super::forms::VIEW_ITEMS),
|
||||
kind: CommandKind::Session,
|
||||
requires: &[],
|
||||
run: |s, p| change(s, p, Change::Show),
|
||||
};
|
||||
|
||||
pub const ISOLATE: CommandSpec = CommandSpec {
|
||||
id: "view.isolate",
|
||||
label: "Isolate",
|
||||
params: concat!(
|
||||
r#"{"items": [{"kind": "body" | "surface" | "datum" | "boundary_condition" | "load" | "reference_point" | "coupling", "name": "Sym"}]}"#,
|
||||
" — shows only these items: every other one is hidden (view.show_all brings them back)"
|
||||
),
|
||||
form: Some(super::forms::VIEW_ITEMS),
|
||||
kind: CommandKind::Session,
|
||||
requires: &[],
|
||||
run: |s, p| change(s, p, Change::Isolate),
|
||||
};
|
||||
|
||||
pub const SHOW_ALL: CommandSpec = CommandSpec {
|
||||
id: "view.show_all",
|
||||
label: "Show All",
|
||||
params: "{}",
|
||||
form: Some(&[]),
|
||||
kind: CommandKind::Session,
|
||||
requires: &[],
|
||||
run: |s, _| {
|
||||
s.view.hidden.clear();
|
||||
Ok(Value::Null)
|
||||
},
|
||||
};
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Change {
|
||||
Hide,
|
||||
Show,
|
||||
Isolate,
|
||||
}
|
||||
|
||||
/// Every item of `kind` the session has, by name.
|
||||
pub(crate) fn names(s: &Session, kind: ItemKind) -> Vec<String> {
|
||||
let m = &s.model;
|
||||
match kind {
|
||||
ItemKind::Body => s.design.iter().flat_map(|d| d.bodies.iter().map(|b| b.name.clone())).collect(),
|
||||
ItemKind::Surface => s.surfaces.iter().map(|x| x.name.clone()).collect(),
|
||||
ItemKind::Datum => m.datums().keys().cloned().collect(),
|
||||
ItemKind::BoundaryCondition => m.boundary_conditions().keys().cloned().collect(),
|
||||
ItemKind::Load => m.loads().keys().cloned().collect(),
|
||||
ItemKind::ReferencePoint => m.reference_points().keys().cloned().collect(),
|
||||
ItemKind::Coupling => m.couplings().keys().cloned().collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn exists(s: &Session, item: &Item) -> bool {
|
||||
let m = &s.model;
|
||||
match item.kind {
|
||||
ItemKind::Body => s.design.as_ref().is_some_and(|d| d.body(&item.name).is_some()),
|
||||
ItemKind::Surface => s.surfaces.iter().any(|x| x.name == item.name),
|
||||
ItemKind::Datum => m.datum(&item.name).is_some(),
|
||||
ItemKind::BoundaryCondition => m.boundary_conditions().contains_key(&item.name),
|
||||
ItemKind::Load => m.loads().contains_key(&item.name),
|
||||
ItemKind::ReferencePoint => m.reference_points().contains_key(&item.name),
|
||||
ItemKind::Coupling => m.couplings().contains_key(&item.name),
|
||||
}
|
||||
}
|
||||
|
||||
/// Forget hidden items the session no longer has.
|
||||
pub(crate) fn forget_missing(s: &mut Session) {
|
||||
if s.view.hidden.is_empty() {
|
||||
return;
|
||||
}
|
||||
let gone: Vec<Item> = s.view.hidden.iter().filter(|i| !exists(s, i)).cloned().collect();
|
||||
for i in gone {
|
||||
s.view.hidden.remove(&i);
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The analysis setup's symbols, without the definitions the view hides.
|
||||
pub fn glyphs(&self) -> fieldcraft_render::glyphs::Glyphs {
|
||||
use fieldcraft_render::glyphs::Definition;
|
||||
fieldcraft_render::glyphs::Glyphs::from_model_hiding(&self.model, &|definition, name| {
|
||||
let kind = match definition {
|
||||
Definition::BoundaryCondition => ItemKind::BoundaryCondition,
|
||||
Definition::Load => ItemKind::Load,
|
||||
Definition::ReferencePoint => ItemKind::ReferencePoint,
|
||||
Definition::Coupling => ItemKind::Coupling,
|
||||
Definition::Contact | Definition::Tie | Definition::Step => return false,
|
||||
};
|
||||
self.view.is_hidden(kind, name)
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the view shows item `name` of `kind`.
|
||||
pub fn shows(&self, kind: ItemKind, name: &str) -> bool {
|
||||
!self.view.is_hidden(kind, name)
|
||||
}
|
||||
}
|
||||
|
||||
fn change(s: &mut Session, p: &Value, how: Change) -> Result<Value> {
|
||||
let items: Vec<Item> = super::req(p, "items")?;
|
||||
if items.len() > MAX_HIDDEN {
|
||||
return Err(EngineError::Params(format!("at most {MAX_HIDDEN} items")));
|
||||
}
|
||||
if let Some(i) = items.iter().find(|i| !exists(s, i)) {
|
||||
let kind = serde_json::to_value(i.kind).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default();
|
||||
return Err(EngineError::Params(format!("no {} `{}`", kind.replace('_', " "), i.name.chars().take(100).collect::<String>())));
|
||||
}
|
||||
match how {
|
||||
Change::Hide => s.view.hidden.extend(items),
|
||||
Change::Show => {
|
||||
for i in &items {
|
||||
s.view.hidden.remove(i);
|
||||
}
|
||||
}
|
||||
Change::Isolate => {
|
||||
let keep: BTreeSet<Item> = items.into_iter().collect();
|
||||
let all = ItemKind::ALL.into_iter().flat_map(|kind| names(s, kind).into_iter().map(move |name| Item { kind, name }));
|
||||
let rest: BTreeSet<Item> = all.filter(|i| !keep.contains(i)).take(MAX_HIDDEN).collect();
|
||||
s.view.hidden = rest;
|
||||
}
|
||||
}
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
|
||||
use super::*;
|
||||
use crate::cmd::datum::tests::plate;
|
||||
|
||||
fn item(kind: ItemKind, name: &str) -> Value {
|
||||
json!({"kind": kind, "name": name})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hiding_is_saved_view_state_not_an_edit() {
|
||||
let (mut s, dir) = plate();
|
||||
s.execute("geometry.datum", &json!({"name": "Sym", "by": {"type": "offset", "plane": "zx"}})).unwrap();
|
||||
s.execute("geometry.datum.point", &json!({"name": "P", "by": {"type": "coordinates", "point": [1, 2, 3]}})).unwrap();
|
||||
let file = dir.join("hide.fieldcraft");
|
||||
s.execute("file.save_as", &json!({"path": file.to_str().unwrap()})).unwrap();
|
||||
let (journal, revision) = (s.journal.len(), s.revision());
|
||||
assert!(!s.is_dirty());
|
||||
|
||||
s.execute("view.hide", &json!({"items": [item(ItemKind::Datum, "Sym")]})).unwrap();
|
||||
assert_eq!(s.view.hidden.iter().collect::<Vec<_>>(), [&Item { kind: ItemKind::Datum, name: "Sym".into() }]);
|
||||
// Unsaved, but no edit: nothing journalled, the revision (and so any result) unchanged.
|
||||
assert!(s.is_dirty());
|
||||
assert_eq!((s.journal.len(), s.revision()), (journal, revision));
|
||||
// Showing it again is back to the saved state.
|
||||
s.execute("view.show", &json!({"items": [item(ItemKind::Datum, "Sym")]})).unwrap();
|
||||
assert!(!s.is_dirty());
|
||||
|
||||
// Hidden state survives save and open.
|
||||
s.execute("view.hide", &json!({"items": [item(ItemKind::Datum, "Sym")]})).unwrap();
|
||||
s.execute("file.save", &json!({})).unwrap();
|
||||
let mut t = Session::default();
|
||||
t.execute("file.open", &json!({"path": file.to_str().unwrap()})).unwrap();
|
||||
assert!(t.view.is_hidden(ItemKind::Datum, "Sym") && !t.view.is_hidden(ItemKind::Datum, "P"));
|
||||
assert!(!t.is_dirty());
|
||||
|
||||
// Isolate hides every other item; show_all brings them back.
|
||||
let body = names(&t, ItemKind::Body).remove(0);
|
||||
t.execute("view.isolate", &json!({"items": [item(ItemKind::Datum, "P")]})).unwrap();
|
||||
assert!(t.view.is_hidden(ItemKind::Body, &body) && t.view.is_hidden(ItemKind::Datum, "Sym") && !t.view.is_hidden(ItemKind::Datum, "P"));
|
||||
t.execute("view.show_all", &json!({})).unwrap();
|
||||
assert!(t.view.is_empty());
|
||||
|
||||
// An item deleted is forgotten.
|
||||
t.execute("view.hide", &json!({"items": [item(ItemKind::Datum, "P")]})).unwrap();
|
||||
t.execute("geometry.datum.delete", &json!({"name": "P"})).unwrap();
|
||||
assert!(t.view.is_empty());
|
||||
|
||||
// Unknown items and hostile parameters change nothing.
|
||||
for p in [json!({}), json!({"items": "x"}), json!({"items": [item(ItemKind::Load, "Nope")]}), json!({"items": [{"kind": "x", "name": "A"}]})]
|
||||
{
|
||||
assert!(t.execute("view.hide", &p).is_err(), "{p}");
|
||||
}
|
||||
assert!(t.view.is_empty());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
use super::*;
|
||||
use crate::Session;
|
||||
|
||||
fn fresh_dir(name: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("fieldcraft-crash-test-{name}-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&d);
|
||||
d
|
||||
}
|
||||
|
||||
fn build() -> Build {
|
||||
Build { version: "9.9.9", commit: "abc1234" }
|
||||
}
|
||||
|
||||
fn node(label: u32) -> Value {
|
||||
json!({"label": label, "xyz": [f64::from(label), 0.0, 0.0]})
|
||||
}
|
||||
|
||||
/// The child half of the process tests: does nothing unless a parent asks, then installs the
|
||||
/// hook and crashes the way `FIELDCRAFT_CRASH_CHILD` says.
|
||||
#[test]
|
||||
fn child() {
|
||||
let (Some(dir), Ok(mode)) = (std::env::var_os("FIELDCRAFT_CRASH_CHILD_DIR"), std::env::var("FIELDCRAFT_CRASH_CHILD")) else {
|
||||
return;
|
||||
};
|
||||
let dir = PathBuf::from(dir);
|
||||
if mode == "replay" {
|
||||
// Replay the one report (in a process of its own: the replay replaces the panic hook).
|
||||
let id = list(&dir)[0].id.clone();
|
||||
let r = replay(&read(&dir, &id).unwrap(), &std::env::temp_dir()).unwrap();
|
||||
let steps: Vec<_> = r.steps.iter().map(|(c, r)| json!({"command": c, "ok": r.is_ok()})).collect();
|
||||
println!("REPLAY {}", json!({"reproduced": r.reproduced, "nodes": r.session.model.nodes().len(), "steps": steps}));
|
||||
return;
|
||||
}
|
||||
let fresh = install(dir.clone(), build());
|
||||
println!("FRESH {}", serde_json::to_string(&fresh).unwrap());
|
||||
if mode == "idle" {
|
||||
end_session();
|
||||
return;
|
||||
}
|
||||
let mut s = Session { crash_journal: true, ..Default::default() };
|
||||
s.execute("mesh.node.add", &node(1)).unwrap();
|
||||
s.execute("mesh.node.add", &node(2)).unwrap();
|
||||
// Commands that only read are not kept.
|
||||
for _ in 0..50 {
|
||||
s.execute("model.info", &json!({})).unwrap();
|
||||
}
|
||||
match mode.as_str() {
|
||||
"command" => {
|
||||
for _ in 0..3 {
|
||||
let r = s.execute("diagnostics.crash_test", &json!({"mode": "panic"}));
|
||||
assert!(matches!(r, Err(crate::EngineError::Internal { .. })), "{r:?}");
|
||||
}
|
||||
assert_eq!(s.model.nodes().len(), 2, "the model is unchanged");
|
||||
}
|
||||
"recovered" => {
|
||||
assert_eq!(s.execute("diagnostics.crash_test", &json!({"mode": "recovered"})).unwrap()["caught"], true);
|
||||
}
|
||||
"thread" => {
|
||||
let r = std::thread::Builder::new()
|
||||
.name("worker".into())
|
||||
.spawn(|| std::panic::panic_any(String::from("worker thread 42 failed")))
|
||||
.unwrap()
|
||||
.join();
|
||||
assert!(r.is_err());
|
||||
}
|
||||
"abort" => {
|
||||
activity("control ui.capture");
|
||||
let _ = s.execute("diagnostics.crash_test", &json!({"mode": "abort"}));
|
||||
}
|
||||
"autosave" => {
|
||||
// The journal starts again from each autosave.
|
||||
let mut a = crate::autosave::Autosaver::new(&dir.join("recovery")).unwrap();
|
||||
assert!(a.save(&s).unwrap());
|
||||
s.execute("mesh.node.add", &node(3)).unwrap();
|
||||
activity("control ui.capture");
|
||||
std::process::abort();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
end_session();
|
||||
}
|
||||
|
||||
/// Run [`child`] in a new process; returns its stdout and whether it succeeded.
|
||||
fn run_child(dir: &Path, mode: &str) -> (String, bool) {
|
||||
let out = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", "crash::tests::child", "--test-threads=1", "--nocapture"])
|
||||
.env("FIELDCRAFT_CRASH_CHILD_DIR", dir)
|
||||
.env("FIELDCRAFT_CRASH_CHILD", mode)
|
||||
.env("FIELDCRAFT_CRASH_TEST", "1")
|
||||
.env("RUST_BACKTRACE", "0")
|
||||
.output()
|
||||
.unwrap();
|
||||
(String::from_utf8_lossy(&out.stdout).into_owned(), out.status.success())
|
||||
}
|
||||
|
||||
fn printed(out: &str, tag: &str) -> Value {
|
||||
let line = out.lines().find_map(|l| l.split_once(tag).map(|(_, rest)| rest)).unwrap_or_else(|| panic!("no {tag} in {out}"));
|
||||
serde_json::from_str(line.trim()).unwrap()
|
||||
}
|
||||
|
||||
fn only_report(dir: &Path) -> (Summary, Value) {
|
||||
let all = list(dir);
|
||||
assert_eq!(all.len(), 1, "{all:?}");
|
||||
let s = all.into_iter().next().unwrap();
|
||||
let v = read(dir, &s.id).unwrap();
|
||||
(s, v)
|
||||
}
|
||||
|
||||
fn nodes_in(model: &str) -> usize {
|
||||
let mut s = Session::default();
|
||||
s.execute("file.open", &json!({"path": model})).unwrap();
|
||||
s.model.nodes().len()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_command_panic_is_reported_once_with_the_model_and_the_command_and_replays() {
|
||||
let d = fresh_dir("command");
|
||||
let (_, ok) = run_child(&d, "command");
|
||||
assert!(ok, "the panics were caught");
|
||||
let (s, v) = only_report(&d);
|
||||
assert_eq!(s.kind, "command_panic");
|
||||
assert_eq!(s.count, 3, "repeats are counted, not written again");
|
||||
assert_eq!(s.command.as_deref(), Some("diagnostics.crash_test"));
|
||||
assert!(s.replayable);
|
||||
assert_eq!(v["format"], FORMAT);
|
||||
assert_eq!(v["app"]["version"], "9.9.9");
|
||||
assert_eq!(v["system"]["os"], std::env::consts::OS);
|
||||
assert!(v["message"].as_str().unwrap().contains("an internal error in a command"), "{v}");
|
||||
assert!(v["location"].as_str().unwrap().contains("diagnostics.rs"), "{v}");
|
||||
let bt = v["backtrace"].as_array().unwrap();
|
||||
assert!(bt.iter().any(|f| f.as_str().unwrap().contains("crash_test")), "{bt:?}");
|
||||
assert!(!bt.iter().any(|f| f.as_str().unwrap().contains("crash::hook")), "the hook's own frames are dropped: {bt:?}");
|
||||
assert_eq!(v["recent_commands"][0]["command"], "mesh.node.add");
|
||||
assert_eq!(v["recent_commands"].as_array().unwrap().len(), 3, "read-only commands are not kept: {v}");
|
||||
assert_eq!(v["recent_commands"][2]["ok"], false);
|
||||
// The model from before the command, and the command: together they reproduce the crash.
|
||||
assert_eq!(nodes_in(v["model_path"].as_str().unwrap()), 2);
|
||||
let replay: Value = serde_json::from_slice(&fs::read(v["replay_path"].as_str().unwrap()).unwrap()).unwrap();
|
||||
assert_eq!(replay["commands"], json!([{"command": "diagnostics.crash_test", "params": {"mode": "panic"}}]));
|
||||
assert_eq!(v["reproduce"], format!("fieldcraft-cli crashes replay {}", s.id));
|
||||
assert!(fs::read_dir(d.join("sessions")).unwrap().next().is_none(), "a clean exit leaves no journal");
|
||||
// The replay reaches the same internal error, from the same model.
|
||||
let (out, ok) = run_child(&d, "replay");
|
||||
assert!(ok, "{out}");
|
||||
let r = printed(&out, "REPLAY ");
|
||||
assert_eq!(r["reproduced"], true, "{r}");
|
||||
assert_eq!(r["nodes"], 2, "the replay ends in the state the crash left: {r}");
|
||||
let _ = fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_panic_caught_inside_a_command_is_reported_as_recovered() {
|
||||
let d = fresh_dir("recovered");
|
||||
let (_, ok) = run_child(&d, "recovered");
|
||||
assert!(ok);
|
||||
let (s, v) = only_report(&d);
|
||||
assert_eq!(s.kind, "recovered_panic");
|
||||
assert!(!s.replayable, "the command did not fail");
|
||||
assert!(v["message"].as_str().unwrap().contains("caught inside"), "{v}");
|
||||
let _ = fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_panic_outside_commands_is_reported_from_the_journal() {
|
||||
let d = fresh_dir("thread");
|
||||
let (_, ok) = run_child(&d, "thread");
|
||||
assert!(ok);
|
||||
let (s, v) = only_report(&d);
|
||||
assert_eq!(s.kind, "panic");
|
||||
assert_eq!(v["thread"], "worker");
|
||||
assert!(s.message.contains("worker thread 42 failed"));
|
||||
// The journal's commands from a new model rebuild it.
|
||||
let replay: Value = serde_json::from_slice(&fs::read(v["replay_path"].as_str().unwrap()).unwrap()).unwrap();
|
||||
assert_eq!(replay["commands"].as_array().unwrap().len(), 2, "{replay}");
|
||||
// A panic the hook reported is no unclean exit at the next start.
|
||||
let (out, _) = run_child(&d, "abort");
|
||||
let fresh = printed(&out, "FRESH ");
|
||||
assert_eq!(fresh.as_array().unwrap().len(), 1, "the earlier report, seen once: {fresh}");
|
||||
let _ = fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unclean_exit_is_found_at_the_next_start_with_its_commands() {
|
||||
let d = fresh_dir("abort");
|
||||
let (_, ok) = run_child(&d, "abort");
|
||||
assert!(!ok, "the child aborted");
|
||||
assert!(list(&d).is_empty(), "nothing wrote a report while it died");
|
||||
assert_eq!(fs::read_dir(d.join("sessions")).unwrap().count(), 1, "its journal is left behind");
|
||||
let (out, ok) = run_child(&d, "idle");
|
||||
assert!(ok);
|
||||
let fresh = printed(&out, "FRESH ");
|
||||
assert_eq!(fresh[0]["kind"], "unclean_exit", "{fresh}");
|
||||
let (s, v) = only_report(&d);
|
||||
assert_eq!(s.command.as_deref(), Some("diagnostics.crash_test"), "the command in flight");
|
||||
assert!(s.message.contains("ended without a clean exit while running `diagnostics.crash_test`"), "{}", s.message);
|
||||
assert_eq!(v["last_activity"], "control ui.capture");
|
||||
let replay: Value = serde_json::from_slice(&fs::read(v["replay_path"].as_str().unwrap()).unwrap()).unwrap();
|
||||
let ids: Vec<&str> = replay["commands"].as_array().unwrap().iter().map(|c| c["command"].as_str().unwrap()).collect();
|
||||
assert_eq!(ids, ["mesh.node.add", "mesh.node.add", "diagnostics.crash_test"]);
|
||||
assert!(fs::read_dir(d.join("sessions")).unwrap().next().is_none(), "the dead journal is gone");
|
||||
// Told once: the next start offers nothing new.
|
||||
let (out, _) = run_child(&d, "idle");
|
||||
assert_eq!(printed(&out, "FRESH "), json!([]));
|
||||
let _ = fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unclean_exit_after_an_autosave_starts_from_the_autosave() {
|
||||
let d = fresh_dir("autosave");
|
||||
let (_, ok) = run_child(&d, "autosave");
|
||||
assert!(!ok);
|
||||
run_child(&d, "idle");
|
||||
let (s, v) = only_report(&d);
|
||||
assert_eq!(s.kind, "unclean_exit");
|
||||
assert!(s.message.contains("between commands (last: control ui.capture)"), "{}", s.message);
|
||||
assert_eq!(nodes_in(v["model_path"].as_str().unwrap()), 2, "the autosaved model");
|
||||
let replay: Value = serde_json::from_slice(&fs::read(v["replay_path"].as_str().unwrap()).unwrap()).unwrap();
|
||||
assert_eq!(replay["commands"], json!([{"command": "mesh.node.add", "params": node(3)}]), "only what came after the autosave");
|
||||
let (out, ok) = run_child(&d, "replay");
|
||||
assert!(ok, "{out}");
|
||||
assert_eq!(printed(&out, "REPLAY ")["nodes"], 3, "the replay rebuilds the model the app had");
|
||||
let _ = fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn journals_parse_and_hostile_ids_are_refused() {
|
||||
let text = [
|
||||
r#"{"start":"x","pid":1,"version":"1"}"#,
|
||||
r#"{"base":"new"}"#,
|
||||
r#"{"run":"a","params":{}}"#,
|
||||
r#"{"ok":true}"#,
|
||||
r#"{"activity":"control ui.capture"}"#,
|
||||
r#"{"run":"b","params":{"x":1}}"#,
|
||||
r#"{"ok":false,"error":"no"}"#,
|
||||
"not json",
|
||||
r#"{"run":"c","params":{}}"#,
|
||||
]
|
||||
.join("\n");
|
||||
let j = parse_journal(&text);
|
||||
assert_eq!(j.replay, vec![json!({"command": "a", "params": {}})]);
|
||||
assert_eq!(j.recent.len(), 2);
|
||||
assert_eq!(j.in_flight, Some(json!({"command": "c", "params": {}})));
|
||||
assert_eq!(j.activity.as_deref(), Some("control ui.capture"));
|
||||
assert!(j.complete && !j.reported);
|
||||
let d = fresh_dir("hostile");
|
||||
fs::create_dir_all(&d).unwrap();
|
||||
for id in ["", "../x", "a/b", &"f".repeat(65)] {
|
||||
assert!(read(&d, id).is_err(), "{id}");
|
||||
assert_eq!(clear(&d, Some(id)), 0);
|
||||
}
|
||||
let _ = fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signatures_ignore_numbers() {
|
||||
assert_eq!(signature("a.rs:1", "node 12 of 400"), signature("a.rs:1", "node 7 of 3"));
|
||||
assert_ne!(signature("a.rs:1", "node 12"), signature("a.rs:2", "node 12"));
|
||||
assert_eq!(utc(0), "1970-01-01T00:00:00Z");
|
||||
assert_eq!(stamp(1_760_436_000), "20251014-100000");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reports_are_pruned_to_the_limits() {
|
||||
let d = fresh_dir("prune");
|
||||
for i in 0..(MAX_REPORTS + 5) {
|
||||
let id = format!("20261014-1000{:02}-{:016x}", i % 60, i + 1);
|
||||
fs::create_dir_all(d.join(&id)).unwrap();
|
||||
let kind = if i == MAX_REPORTS + 4 { "recovered_panic" } else { "panic" };
|
||||
fs::write(d.join(&id).join("report.json"), json!({"kind": kind, "message": "m"}).to_string()).unwrap();
|
||||
}
|
||||
prune(&d, now());
|
||||
let left = list(&d);
|
||||
assert_eq!(left.len(), MAX_REPORTS);
|
||||
assert!(left.iter().all(|r| r.kind == "panic"), "recovered ones go first");
|
||||
assert_eq!(clear(&d, None), MAX_REPORTS);
|
||||
let _ = fs::remove_dir_all(&d);
|
||||
}
|
||||
@@ -6,6 +6,11 @@
|
||||
//! journal always replays to the current model, and the undo steps are the journal's last
|
||||
//! entries, newest last. A new command clears the redo stack.
|
||||
//!
|
||||
//! A step also carries the session's [`Document`] (its file and the revision saved there) when
|
||||
//! its command changed which document the session is, as `geometry.open` with `"model": "new"`
|
||||
//! does: undo makes the previous file current again, redo the new untitled model. Other steps
|
||||
//! leave the document alone, so saving between edits and then undoing them keeps the file.
|
||||
//!
|
||||
//! History is bounded by step count ([`MAX_UNDO_STEPS`]) and by an estimate of the memory the
|
||||
//! kept states hold ([`DEFAULT_UNDO_MEMORY`], [`Session::set_undo_memory`]): when either is
|
||||
//! exceeded, the oldest undo steps go first, then the redo steps farthest from the current state.
|
||||
@@ -46,6 +51,16 @@ pub(crate) struct State {
|
||||
surfaces: Vec<Arc<TaggedSurface>>,
|
||||
sources: fieldcraft_io::Geometry,
|
||||
revision: u64,
|
||||
/// The document before the step, when the step changed it.
|
||||
pub(crate) document: Option<Document>,
|
||||
}
|
||||
|
||||
/// Which document the session is: the `.fieldcraft` file it belongs to and the revision saved
|
||||
/// there ([`Session::is_dirty`]).
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub(crate) struct Document {
|
||||
pub(crate) path: Option<String>,
|
||||
pub(crate) saved_revision: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -147,6 +162,19 @@ impl Session {
|
||||
surfaces: self.surfaces.clone(),
|
||||
sources: self.sources.clone(),
|
||||
revision: self.revision,
|
||||
document: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn document(&self) -> Document {
|
||||
Document { path: self.path.clone(), saved_revision: self.saved_revision }
|
||||
}
|
||||
|
||||
/// Make `document` current; returns the one it replaces.
|
||||
pub(crate) fn set_document(&mut self, document: Document) -> Document {
|
||||
Document {
|
||||
path: std::mem::replace(&mut self.path, document.path),
|
||||
saved_revision: std::mem::replace(&mut self.saved_revision, document.saved_revision),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,6 +186,7 @@ impl Session {
|
||||
surfaces: std::mem::replace(&mut self.surfaces, state.surfaces),
|
||||
sources: std::mem::replace(&mut self.sources, state.sources),
|
||||
revision: std::mem::replace(&mut self.revision, state.revision),
|
||||
document: state.document.map(|d| self.set_document(d)),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,14 +13,23 @@
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
pub mod autosave;
|
||||
pub mod bug_report;
|
||||
pub mod catalogue;
|
||||
pub mod cmd;
|
||||
pub mod crash;
|
||||
pub mod logfile;
|
||||
|
||||
pub use cmd::analytic_surfaces;
|
||||
pub use cmd::replace::{MESHERS, Replacement, replacement};
|
||||
pub use cmd::update::enable_checks as enable_update_checks;
|
||||
pub use fieldcraft_io::{Item as ViewItem, ItemKind};
|
||||
pub mod history;
|
||||
pub mod progress;
|
||||
pub mod requirement;
|
||||
pub mod results;
|
||||
pub mod sample;
|
||||
pub mod schema;
|
||||
pub mod usage;
|
||||
pub mod view;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
@@ -40,6 +49,11 @@ pub enum EngineError {
|
||||
UnknownCommand(String),
|
||||
#[error("{0}")]
|
||||
Params(String),
|
||||
/// One parameter is missing or wrong: the schema's [`schema::Problem`], at the field's JSON
|
||||
/// path (`elastic/young`). The message names the key ([`schema::Problem::for_agents`]); a
|
||||
/// form shows it beside the field, by its label ([`schema::Problem::for_form`]).
|
||||
#[error("{}", .0.for_agents())]
|
||||
Param(schema::Problem),
|
||||
#[error(transparent)]
|
||||
Model(#[from] fieldcraft_model::Error),
|
||||
#[error(transparent)]
|
||||
@@ -56,11 +70,27 @@ pub enum EngineError {
|
||||
Explicit(#[from] fieldcraft_explicit::Error),
|
||||
#[error(transparent)]
|
||||
Fluid(#[from] fieldcraft_lbm::Error),
|
||||
/// The session lacks what the command needs ([`requirement`]); nothing was done.
|
||||
#[error("{0}")]
|
||||
Unavailable(requirement::Unavailable),
|
||||
/// A command panicked; the model is unchanged.
|
||||
#[error("internal error in {command}: {message}")]
|
||||
Internal { command: String, message: String },
|
||||
}
|
||||
|
||||
impl EngineError {
|
||||
/// A problem with the parameter at `path` (`elastic/young`).
|
||||
pub fn param(path: impl Into<String>, kind: schema::ProblemKind) -> Self {
|
||||
Self::Param(schema::Problem::at(path, kind))
|
||||
}
|
||||
|
||||
/// A parameter problem with something wrong that the schema does not describe: what the
|
||||
/// value must be or do instead.
|
||||
pub fn invalid(path: impl Into<String>, why: impl Into<String>) -> Self {
|
||||
Self::param(path, schema::ProblemKind::Invalid(why.into()))
|
||||
}
|
||||
}
|
||||
|
||||
pub type Result<T> = std::result::Result<T, EngineError>;
|
||||
|
||||
/// The result of a solved step, from the implicit, the explicit or the lattice Boltzmann solver.
|
||||
@@ -113,6 +143,9 @@ pub struct CommandSpec {
|
||||
/// (the form is then the JSON text alone).
|
||||
pub form: Option<&'static [schema::Field]>,
|
||||
pub kind: CommandKind,
|
||||
/// What the session must hold before the command can run ([`requirement`]): checked by
|
||||
/// [`Session::execute`], and by the UI to grey the command with the missing pieces named.
|
||||
pub requires: &'static [requirement::Requirement],
|
||||
pub run: fn(&mut Session, &Value) -> Result<Value>,
|
||||
}
|
||||
|
||||
@@ -124,9 +157,9 @@ pub fn commands() -> &'static [CommandSpec] {
|
||||
impl CommandSpec {
|
||||
/// The command as JSON for listings (`fieldcraft-cli commands --json`, the control channel's
|
||||
/// `engine.commands`, MCP `list_commands`): id, label, the parameter doc and, when described,
|
||||
/// the parameters as JSON Schema.
|
||||
/// the parameters as JSON Schema, and what it requires.
|
||||
pub fn listing(&self) -> Value {
|
||||
let mut v = serde_json::json!({"id": self.id, "label": self.label, "params": self.params});
|
||||
let mut v = serde_json::json!({"id": self.id, "label": self.label, "params": self.params, "requires": self.requires});
|
||||
if let Some(form) = self.form {
|
||||
v["schema"] = schema::json_schema(form);
|
||||
}
|
||||
@@ -208,6 +241,21 @@ pub struct Session {
|
||||
/// The folders commands may read and write files in (an automation client's roots,
|
||||
/// docs/mcp.md); unconfined by default. A file replacing the session keeps them.
|
||||
pub file_access: fieldcraft_io::roots::Roots,
|
||||
/// Identifies the open document: it changes when another model, sample or design is opened
|
||||
/// in place of the current one, never with an edit (see [`Session::opened`]).
|
||||
opened: u64,
|
||||
/// What the viewport hides (`view.*`): saved with the model, but no edit of it, so it is
|
||||
/// neither journalled nor undone, and it leaves results current.
|
||||
pub view: fieldcraft_io::View,
|
||||
/// The view as last saved (or opened): a change to it is unsaved too.
|
||||
saved_view: fieldcraft_io::View,
|
||||
/// This is the app's own model: its top-level commands go into the crash journal
|
||||
/// ([`crash`]), so an unclean exit can be replayed. Off for scratch sessions and tests.
|
||||
pub crash_journal: bool,
|
||||
/// Where this session's commands come from, for the usage analytics ([`usage`]): the app
|
||||
/// sets it on its own model (and the control channel and the command search while they
|
||||
/// run); `None` (scratch sessions, the CLI, tests) counts nothing.
|
||||
pub origin: Option<usage::Origin>,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
@@ -216,11 +264,33 @@ impl Session {
|
||||
pub fn execute(&mut self, id: &str, params: &Value) -> Result<Value> {
|
||||
// An id from hostile input is not echoed in full.
|
||||
let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.chars().take(100).collect()))?;
|
||||
let timer = usage::Timer::start(self.origin);
|
||||
let elements = self.model.elements().len();
|
||||
let result = self.availability(spec).map_err(EngineError::Unavailable).and_then(|()| self.run_command(spec, params));
|
||||
if timer.counting() {
|
||||
let milestone = usage::milestone(spec.id, (elements, self.model.elements().len()));
|
||||
let sample =
|
||||
(spec.id == "file.sample").then(|| params.get("name").and_then(Value::as_str).and_then(sample::find)).flatten().map(|s| s.name);
|
||||
timer.done(spec.id, spec.kind, result.as_ref().err(), milestone, sample);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// [`Session::execute`] once the command is found and can run.
|
||||
fn run_command(&mut self, spec: &'static CommandSpec, params: &Value) -> Result<Value> {
|
||||
let id = spec.id;
|
||||
// Session commands (open, save, undo, redo) change the session only in their last step,
|
||||
// after everything that can fail, so they need no copy of the model to restore.
|
||||
let before = (spec.kind == CommandKind::Model).then(|| self.snapshot());
|
||||
let before = (spec.kind == CommandKind::Model).then(|| (self.snapshot(), self.document()));
|
||||
let scope = crash::Scope::enter();
|
||||
let journaled = crash::command_begin(&scope, self, id, params);
|
||||
let (revision, opened) = (self.revision, self.opened);
|
||||
let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (spec.run)(self, params)));
|
||||
let result = match outcome {
|
||||
Ok(Err(EngineError::Param(p))) => Err(EngineError::Param(match spec.form {
|
||||
Some(form) => schema::refine(form, params, p),
|
||||
None => p,
|
||||
})),
|
||||
Ok(r) => r,
|
||||
Err(p) => {
|
||||
let message = p.downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| p.downcast_ref::<String>().cloned()).unwrap_or_default();
|
||||
@@ -228,15 +298,24 @@ impl Session {
|
||||
Err(EngineError::Internal { command: id.to_string(), message })
|
||||
}
|
||||
};
|
||||
if let Some(before) = before {
|
||||
if let Some((mut before, document)) = before {
|
||||
// A command that makes the session another document (a new model) keeps the old
|
||||
// one in its undo step.
|
||||
if self.document() != document {
|
||||
before.document = Some(document);
|
||||
}
|
||||
if result.is_err() {
|
||||
self.restore(before);
|
||||
} else if self.differs_from(&before) {
|
||||
} else if before.document.is_some() || self.differs_from(&before) {
|
||||
self.journal.push((id.to_string(), params.clone()));
|
||||
self.revision = next_revision();
|
||||
self.record_undo(before);
|
||||
// An item deleted (or a body cut into cells) is no longer hidden.
|
||||
cmd::view::forget_missing(self);
|
||||
}
|
||||
}
|
||||
drop(scope);
|
||||
crash::command_done(self, journaled, self.revision != revision || self.opened != opened, id, params, &result);
|
||||
result
|
||||
}
|
||||
|
||||
@@ -254,6 +333,19 @@ impl Session {
|
||||
Ok(outputs)
|
||||
}
|
||||
|
||||
/// Identifies the open document: it changes when `file.open`, `file.recover` or `file.sample`
|
||||
/// replaces the session and when `geometry.open` opens another design file or starts a new
|
||||
/// model with one; an edit, a solve, undo, redo or opening the same design again after an
|
||||
/// edit keep it. A view frames the model again when it changes.
|
||||
pub fn opened(&self) -> u64 {
|
||||
self.opened
|
||||
}
|
||||
|
||||
/// Make the session another document (see [`Session::opened`]).
|
||||
pub(crate) fn mark_opened(&mut self) {
|
||||
self.opened = next_revision();
|
||||
}
|
||||
|
||||
/// Identifies the current state (see [`Session::is_dirty`]).
|
||||
pub fn revision(&self) -> u64 {
|
||||
self.revision
|
||||
@@ -262,7 +354,7 @@ impl Session {
|
||||
/// Whether the session has changes its file does not hold. Undoing back to the saved state
|
||||
/// makes it clean again.
|
||||
pub fn is_dirty(&self) -> bool {
|
||||
self.saved_revision.unwrap_or(0) != self.revision
|
||||
self.saved_revision.unwrap_or(0) != self.revision || self.view != self.saved_view
|
||||
}
|
||||
|
||||
/// The stored result of a step, if it was solved in the current state (an edit makes it stale;
|
||||
@@ -303,6 +395,7 @@ impl Session {
|
||||
pub(crate) fn mark_saved(&mut self, path: String) {
|
||||
self.path = Some(path);
|
||||
self.saved_revision = Some(self.revision);
|
||||
self.saved_view = self.view.clone();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -632,6 +725,10 @@ mod tests {
|
||||
assert!((volume - expect).abs() < 1e-3 * expect, "{volume}");
|
||||
let faces = bodies[0]["faces"].as_array().unwrap();
|
||||
assert_eq!(faces.len(), 8);
|
||||
let edges = bodies[0]["edges"].as_array().unwrap();
|
||||
assert_eq!(edges.len(), 18);
|
||||
// Through the thickness: four box corners, the two hole seams.
|
||||
assert_eq!(edges.iter().filter(|e| (e["length"].as_f64().unwrap() - 10.0).abs() < 1e-6).count(), 6);
|
||||
|
||||
let t = s.execute("geometry.tessellate", &json!({"body": "Body1", "tolerance": 0.05})).unwrap();
|
||||
let per_face: Vec<u64> = t["faces"].as_array().unwrap().iter().map(|f| f["triangles"].as_u64().unwrap()).collect();
|
||||
@@ -649,6 +746,148 @@ mod tests {
|
||||
let wider = s.execute("geometry.bodies", &json!({})).unwrap();
|
||||
assert!(wider[0]["volume"].as_f64().unwrap() > volume);
|
||||
assert_eq!(wider[0]["faces"], bodies[0]["faces"]);
|
||||
let names = |b: &Value| b[0]["edges"].as_array().unwrap().iter().map(|e| e["name"].clone()).collect::<Vec<_>>();
|
||||
assert_eq!(names(&wider), names(&bodies));
|
||||
assert_eq!(s.journal.len(), 2);
|
||||
}
|
||||
|
||||
/// A meshed, defined model of body `body` (a hex block whose bottom face is named `bottom`)
|
||||
/// with a set on it and one on its face `face`.
|
||||
fn defined_model(body: &str, face: &str) -> Session {
|
||||
let mut s = Session::default();
|
||||
let cube = [[0, 0, 0], [10, 0, 0], [10, 10, 0], [0, 10, 0], [0, 0, 10], [10, 0, 10], [10, 10, 10], [0, 10, 10]];
|
||||
let script = json!([
|
||||
{"command": "mesh.block", "params": {"body": body, "kind": "hex8", "corners": cube, "divisions": [1, 1, 1], "faces": {"1": "bottom"}}},
|
||||
{"command": "model.set.create", "params": {"name": "all", "geometry": [{"body": body}]}},
|
||||
{"command": "model.set.create", "params": {"name": "hole", "geometry": [{"body": body, "face": face}]}},
|
||||
{"command": "model.material.create", "params": {"name": "Steel", "elastic": {"type": "isotropic", "young": 210000, "poisson": 0.3}}},
|
||||
]);
|
||||
s.run_script(&script).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// `opened` changes with another document (a sample, another design file, a new model) and
|
||||
/// stays with an edit, a solve or the same design opened again: views frame on that change.
|
||||
#[test]
|
||||
fn the_open_document_changes_only_when_another_is_opened() {
|
||||
let mut s = Session::default();
|
||||
let start = s.opened();
|
||||
s.execute("file.sample", &json!({"name": "cantilever"})).unwrap();
|
||||
let cantilever = s.opened();
|
||||
assert_ne!(cantilever, start);
|
||||
s.execute("solve.run", &json!({})).unwrap();
|
||||
s.execute("model.material.create", &json!({"name": "Al", "elastic": {"type": "isotropic", "young": 70000, "poisson": 0.33}})).unwrap();
|
||||
assert_eq!(s.opened(), cantilever, "edits and solves keep the document");
|
||||
s.execute("file.sample", &json!({"name": "cantilever"})).unwrap();
|
||||
assert_ne!(s.opened(), cantilever, "a sample opened again is a fresh start");
|
||||
|
||||
let (_dir, path) = sample_design_file(&Plate::default());
|
||||
let before = s.opened();
|
||||
s.execute("geometry.open", &json!({"path": path})).unwrap();
|
||||
let design = s.opened();
|
||||
assert_ne!(design, before, "another design file");
|
||||
s.execute("geometry.open", &json!({"path": path})).unwrap();
|
||||
assert_eq!(s.opened(), design, "the same design opened again after an edit");
|
||||
s.execute("geometry.open", &json!({"path": path, "model": "new"})).unwrap();
|
||||
assert_ne!(s.opened(), design, "a new model");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reopening_the_same_design_keeps_the_mesh_and_definitions() {
|
||||
let (_dir, path) = sample_design_file(&Plate::default());
|
||||
let mut probe = Session::default();
|
||||
probe.execute("geometry.open", &json!({"path": path})).unwrap();
|
||||
let faces = probe.execute("geometry.bodies", &json!({})).unwrap()[0]["faces"].clone();
|
||||
let mut s = defined_model("Body1", faces[0]["name"].as_str().unwrap());
|
||||
let before = s.model.clone();
|
||||
let r = s.execute("geometry.open", &json!({"path": path})).unwrap();
|
||||
assert_eq!((r["model"].as_str(), r["related"].as_bool()), (Some("kept"), Some(true)), "{r}");
|
||||
assert_eq!(r["stale"], json!({"mesh_bodies": [], "sets": [], "seeds": []}));
|
||||
assert_eq!(s.model, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_different_design_starts_a_new_model_or_reports_what_is_stale() {
|
||||
let (_dir, path) = sample_design_file(&Plate::default());
|
||||
let defined = defined_model("Seal", "no-such-face");
|
||||
let before = defined.model.clone();
|
||||
assert!(!before.elements().is_empty() && before.sets().len() == 2);
|
||||
|
||||
// Kept (the default): nothing is lost, and the reply names what no longer resolves.
|
||||
let mut kept = defined.clone();
|
||||
let r = kept.execute("geometry.open", &json!({"path": path})).unwrap();
|
||||
assert_eq!((r["model"].as_str(), r["related"].as_bool()), (Some("kept"), Some(false)), "{r}");
|
||||
assert_eq!(r["stale"], json!({"mesh_bodies": ["Seal"], "sets": ["all", "hole"], "seeds": []}));
|
||||
assert_eq!(kept.model, before);
|
||||
|
||||
// New: the mesh and every definition go, the units stay; one undo brings them back.
|
||||
let mut fresh = defined.clone();
|
||||
fresh.execute("model.units", &json!({"system": "m-kg-s-N-Pa"})).unwrap();
|
||||
let units = fresh.model.units();
|
||||
let before = fresh.model.clone();
|
||||
let r = fresh.execute("geometry.open", &json!({"path": path, "model": "new"})).unwrap();
|
||||
assert_eq!((r["model"].as_str(), r["related"].as_bool()), (Some("new"), Some(false)), "{r}");
|
||||
assert_eq!(r["stale"], json!({"mesh_bodies": [], "sets": [], "seeds": []}));
|
||||
assert!(fresh.model.elements().is_empty() && fresh.model.nodes().is_empty());
|
||||
assert!(fresh.model.definition_counts().iter().all(|(_, n)| *n == 0));
|
||||
assert_eq!(fresh.model.units(), units);
|
||||
assert!(fresh.design.is_some());
|
||||
fresh.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(fresh.model, before);
|
||||
assert!(fresh.design.is_none());
|
||||
|
||||
// A bad choice changes nothing.
|
||||
let mut s = defined.clone();
|
||||
assert!(s.execute("geometry.open", &json!({"path": path, "model": "discard"})).is_err());
|
||||
assert!(s.design.is_none() && s.model == defined.model);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_model_is_untitled_and_undo_brings_the_file_back() {
|
||||
let (dir, design) = sample_design_file(&Plate::default());
|
||||
let file = dir.0.join("a.fieldcraft").to_string_lossy().into_owned();
|
||||
let mut s = defined_model("Seal", "no-such-face");
|
||||
s.execute("file.save_as", &json!({"path": file})).unwrap();
|
||||
assert!(!s.is_dirty());
|
||||
|
||||
s.execute("geometry.open", &json!({"path": design, "model": "new"})).unwrap();
|
||||
assert_eq!(s.path, None, "a new model must not save over the old model's file");
|
||||
assert!(s.is_dirty());
|
||||
assert!(s.execute("file.save", &json!({})).is_err(), "save asks for a file");
|
||||
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.path.as_deref(), Some(file.as_str()));
|
||||
assert!(!s.is_dirty(), "undo returns to the saved state of the old file");
|
||||
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(s.path, None);
|
||||
assert!(s.is_dirty());
|
||||
|
||||
// Saving the new model and then editing it: undoing the edit keeps the new file.
|
||||
let b = dir.0.join("b.fieldcraft").to_string_lossy().into_owned();
|
||||
s.execute("file.save_as", &json!({"path": b})).unwrap();
|
||||
s.execute("model.material.create", &json!({"name": "Al", "elastic": {"type": "isotropic", "young": 70000, "poisson": 0.33}})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.path.as_deref(), Some(b.as_str()));
|
||||
assert!(!s.is_dirty());
|
||||
// Undoing the open after that save returns to the old file; redo to the saved new one.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.path.as_deref(), Some(file.as_str()));
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(s.path.as_deref(), Some(b.as_str()));
|
||||
assert!(!s.is_dirty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeping_the_model_keeps_its_file_and_a_sample_has_none() {
|
||||
let (dir, design) = sample_design_file(&Plate::default());
|
||||
let file = dir.0.join("a.fieldcraft").to_string_lossy().into_owned();
|
||||
let mut s = defined_model("Seal", "no-such-face");
|
||||
s.execute("file.save_as", &json!({"path": file})).unwrap();
|
||||
s.execute("geometry.open", &json!({"path": design})).unwrap();
|
||||
assert_eq!(s.path.as_deref(), Some(file.as_str()));
|
||||
s.execute("file.sample", &json!({"name": "cantilever"})).unwrap();
|
||||
assert_eq!(s.path, None, "a sample must not save over the last opened file");
|
||||
assert!(s.execute("file.save", &json!({})).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
//! The log file: what the desktop app logs (through the `log` facade) goes to
|
||||
//! `<data folder>/logs/fieldcraft.log`, one line per record:
|
||||
//! `2026-10-14T10:03:22Z WARN [4242] fieldcraft_engine: message`. Warnings and errors also go to
|
||||
//! the standard error stream.
|
||||
//!
|
||||
//! Bounded: past [`MAX_BYTES`] the file becomes `fieldcraft.log.1` (replacing the one before) and
|
||||
//! a new one starts, so the logs never take more than twice that. A record is cut at
|
||||
//! [`MAX_LINE`] bytes. The process id on every line lets a crash report take only the lines of
|
||||
//! the run that crashed ([`tail`]), even when two apps share the file.
|
||||
//!
|
||||
//! Nothing is installed in tests, the CLI or the web build (which logs to the browser console).
|
||||
|
||||
use std::fs::{self, File, OpenOptions};
|
||||
use std::io::{Read, Seek, SeekFrom, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
|
||||
/// The log file's name.
|
||||
pub const FILE_NAME: &str = "fieldcraft.log";
|
||||
/// The log file's size limit.
|
||||
pub const MAX_BYTES: u64 = 2 << 20;
|
||||
/// A record's size limit.
|
||||
pub const MAX_LINE: usize = 4 << 10;
|
||||
|
||||
struct FileLogger {
|
||||
path: PathBuf,
|
||||
level: log::LevelFilter,
|
||||
out: Mutex<Out>,
|
||||
}
|
||||
|
||||
struct Out {
|
||||
file: Option<File>,
|
||||
bytes: u64,
|
||||
}
|
||||
|
||||
static LOGGER: OnceLock<FileLogger> = OnceLock::new();
|
||||
|
||||
/// Send the `log` records at `level` and above to the log file in `dir` (created if needed).
|
||||
/// Returns the file's path. Call once; later calls change nothing.
|
||||
pub fn install(dir: &Path, level: log::LevelFilter) -> Result<PathBuf, String> {
|
||||
fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
let path = dir.join(FILE_NAME);
|
||||
let file = open(&path).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
let bytes = file.metadata().map_or(0, |m| m.len());
|
||||
let logger = FileLogger { path: path.clone(), level, out: Mutex::new(Out { file: Some(file), bytes }) };
|
||||
if LOGGER.set(logger).is_err() {
|
||||
return Err("a log file is already installed".into());
|
||||
}
|
||||
if let Some(l) = LOGGER.get() {
|
||||
log::set_logger(l).map_err(|e| e.to_string())?;
|
||||
log::set_max_level(level);
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
fn open(path: &Path) -> std::io::Result<File> {
|
||||
OpenOptions::new().create(true).append(true).open(path)
|
||||
}
|
||||
|
||||
/// The log file, once [`install`]ed.
|
||||
pub fn path() -> Option<&'static Path> {
|
||||
LOGGER.get().map(|l| l.path.as_path())
|
||||
}
|
||||
|
||||
/// The last `max` bytes of the log file's lines written by process `pid` (every line when
|
||||
/// `None`), from the rotated file too when the current one is short. `None` without a log file.
|
||||
pub fn tail(pid: Option<u32>, max: usize) -> Option<String> {
|
||||
let path = path().map(Path::to_path_buf).or_else(default_path)?;
|
||||
Some(tail_of(&path, pid, max))
|
||||
}
|
||||
|
||||
/// [`tail`] of the log file at `path`.
|
||||
fn tail_of(path: &Path, pid: Option<u32>, max: usize) -> String {
|
||||
let mut text = String::new();
|
||||
for p in [rotated(path), path.to_path_buf()] {
|
||||
// The whole file (it is bounded): another process's lines may come between.
|
||||
text.push_str(&read_end(&p, MAX_BYTES));
|
||||
}
|
||||
let mark = pid.map(|p| format!(" [{p}] "));
|
||||
let mut lines: Vec<&str> = text.lines().filter(|l| mark.as_deref().is_none_or(|m| l.contains(m))).collect();
|
||||
let mut total = 0;
|
||||
let mut keep = lines.len();
|
||||
for (i, l) in lines.iter().enumerate().rev() {
|
||||
total += l.len() + 1;
|
||||
if total > max {
|
||||
break;
|
||||
}
|
||||
keep = i;
|
||||
}
|
||||
lines.drain(..keep);
|
||||
lines.join("\n")
|
||||
}
|
||||
|
||||
/// The log file of this computer's app (for a crash report written before [`install`]).
|
||||
fn default_path() -> Option<PathBuf> {
|
||||
fieldcraft_io::recovery::data_dir().map(|d| d.join("logs").join(FILE_NAME))
|
||||
}
|
||||
|
||||
/// The file the log rotates into.
|
||||
pub fn rotated(path: &Path) -> PathBuf {
|
||||
let mut s = path.as_os_str().to_owned();
|
||||
s.push(".1");
|
||||
PathBuf::from(s)
|
||||
}
|
||||
|
||||
/// The last `max` bytes of a file, from the start of a line.
|
||||
fn read_end(path: &Path, max: u64) -> String {
|
||||
let Ok(mut f) = File::open(path) else { return String::new() };
|
||||
let len = f.metadata().map_or(0, |m| m.len());
|
||||
let from = len.saturating_sub(max);
|
||||
let mut buf = Vec::new();
|
||||
if f.seek(SeekFrom::Start(from)).is_err() || f.take(max).read_to_end(&mut buf).is_err() {
|
||||
return String::new();
|
||||
}
|
||||
let text = String::from_utf8_lossy(&buf).into_owned();
|
||||
match (from > 0, text.find('\n')) {
|
||||
(true, Some(i)) => text.get(i + 1..).unwrap_or_default().to_string(),
|
||||
_ => text,
|
||||
}
|
||||
}
|
||||
|
||||
impl log::Log for FileLogger {
|
||||
fn enabled(&self, metadata: &log::Metadata<'_>) -> bool {
|
||||
metadata.level() <= self.level
|
||||
}
|
||||
|
||||
fn log(&self, record: &log::Record<'_>) {
|
||||
if !self.enabled(record.metadata()) {
|
||||
return;
|
||||
}
|
||||
let message = crate::crash::limited(&record.args().to_string(), MAX_LINE).replace('\n', "\n ");
|
||||
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs());
|
||||
let line = format!("{} {:<5} [{}] {}: {message}\n", crate::crash::utc(now), record.level(), std::process::id(), record.target());
|
||||
if record.level() <= log::Level::Warn {
|
||||
eprint!("{line}");
|
||||
}
|
||||
let Ok(mut out) = self.out.lock() else { return };
|
||||
if out.bytes + line.len() as u64 > MAX_BYTES {
|
||||
out.file = None;
|
||||
let _ = fs::rename(&self.path, rotated(&self.path));
|
||||
out.file = open(&self.path).ok();
|
||||
out.bytes = 0;
|
||||
}
|
||||
if let Some(f) = &mut out.file
|
||||
&& f.write_all(line.as_bytes()).is_err()
|
||||
{
|
||||
out.file = None;
|
||||
}
|
||||
out.bytes += line.len() as u64;
|
||||
}
|
||||
|
||||
fn flush(&self) {
|
||||
if let Ok(mut out) = self.out.lock()
|
||||
&& let Some(f) = &mut out.file
|
||||
{
|
||||
let _ = f.flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn tail_keeps_one_process_and_the_end() {
|
||||
let d = std::env::temp_dir().join(format!("fieldcraft-logtail-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&d);
|
||||
fs::create_dir_all(&d).unwrap();
|
||||
let p = d.join(FILE_NAME);
|
||||
fs::write(rotated(&p), "t INFO [7] a: old seven\nt INFO [8] a: old eight\n").unwrap();
|
||||
fs::write(&p, "t INFO [7] a: one\nt WARN [8] a: other\nt INFO [7] a: two\n").unwrap();
|
||||
assert_eq!(tail_of(&p, Some(7), 1000), "t INFO [7] a: old seven\nt INFO [7] a: one\nt INFO [7] a: two");
|
||||
assert_eq!(tail_of(&p, Some(7), 40), "t INFO [7] a: one\nt INFO [7] a: two");
|
||||
assert_eq!(tail_of(&p, None, 1000).lines().count(), 5);
|
||||
// From the middle of a line, the partial line is dropped.
|
||||
assert_eq!(read_end(&p, 20), "t INFO [7] a: two\n");
|
||||
let _ = fs::remove_dir_all(&d);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
//! Where the model is in the analysis workflow: the setup checklist ([`Session::progress`]).
|
||||
//!
|
||||
//! The stages run in the usual order — geometry, preparation, mesh, material, section, sets,
|
||||
//! boundary conditions, loads, step, solve, results — each with whether it is done, the next one
|
||||
//! to do, still to do, blocked (its command cannot run yet) or optional, and the command that
|
||||
//! provides it. It is a guide, never a gate: a script can define things in any order, and
|
||||
//! [`crate::requirement`] still decides what each command needs.
|
||||
//!
|
||||
//! Each stage is a [`Requirement`] check (a count), and Solve also reads the model check's first
|
||||
//! error, so the whole list costs one [`fieldcraft_model::Model::check`]: the desktop reads it
|
||||
//! once per model change, and `model.check` returns it as `progress`.
|
||||
|
||||
use fieldcraft_model::{Procedure, Severity};
|
||||
use serde::Serialize;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Session;
|
||||
use crate::requirement::Requirement;
|
||||
|
||||
/// A step of the analysis workflow, in order.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Stage {
|
||||
Geometry,
|
||||
/// Seeds and partitions that steer the mesh (optional).
|
||||
Prepare,
|
||||
Mesh,
|
||||
Material,
|
||||
Section,
|
||||
Sets,
|
||||
BoundaryConditions,
|
||||
Loads,
|
||||
Step,
|
||||
Solve,
|
||||
Results,
|
||||
}
|
||||
|
||||
impl Stage {
|
||||
pub const ALL: [Stage; 11] = [
|
||||
Stage::Geometry,
|
||||
Stage::Prepare,
|
||||
Stage::Mesh,
|
||||
Stage::Material,
|
||||
Stage::Section,
|
||||
Stage::Sets,
|
||||
Stage::BoundaryConditions,
|
||||
Stage::Loads,
|
||||
Stage::Step,
|
||||
Stage::Solve,
|
||||
Stage::Results,
|
||||
];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Stage::Geometry => "Geometry",
|
||||
Stage::Prepare => "Seeds & partitions",
|
||||
Stage::Mesh => "Mesh",
|
||||
Stage::Material => "Material",
|
||||
Stage::Section => "Section",
|
||||
Stage::Sets => "Sets",
|
||||
Stage::BoundaryConditions => "Boundary conditions",
|
||||
Stage::Loads => "Loads",
|
||||
Stage::Step => "Step",
|
||||
Stage::Solve => "Solve",
|
||||
Stage::Results => "Results",
|
||||
}
|
||||
}
|
||||
|
||||
/// What it checks; its provider is the command the stage starts.
|
||||
fn requirement(self) -> Requirement {
|
||||
match self {
|
||||
Stage::Geometry => Requirement::Geometry,
|
||||
Stage::Prepare => Requirement::Seed,
|
||||
Stage::Mesh => Requirement::Analysable,
|
||||
Stage::Material => Requirement::Material,
|
||||
Stage::Section => Requirement::Section,
|
||||
Stage::Sets => Requirement::Set,
|
||||
Stage::BoundaryConditions => Requirement::BoundaryCondition,
|
||||
Stage::Loads => Requirement::Load,
|
||||
Stage::Step => Requirement::Step,
|
||||
Stage::Solve => Requirement::Result,
|
||||
Stage::Results => Requirement::ResultsShown,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a stage is.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Status {
|
||||
Done,
|
||||
/// The first stage still to do.
|
||||
Next,
|
||||
/// Still to do after the next one; its command can already run.
|
||||
Todo,
|
||||
/// Its command cannot run yet (`detail` says why).
|
||||
Blocked,
|
||||
/// Not done, and not needed for this model.
|
||||
Optional,
|
||||
}
|
||||
|
||||
/// One row of the checklist.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
pub struct StageState {
|
||||
pub stage: Stage,
|
||||
pub label: &'static str,
|
||||
pub status: Status,
|
||||
/// The command that does it.
|
||||
pub command: &'static str,
|
||||
/// Where that command is on the toolbar ("Properties › Material").
|
||||
pub place: String,
|
||||
/// Why it is blocked: what its command misses, or the model check's first error.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub detail: Option<String>,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The setup checklist for the current model (one model check).
|
||||
pub fn progress(&self) -> Vec<StageState> {
|
||||
let first_error = self.model.check().into_iter().find(|d| d.severity == Severity::Error);
|
||||
self.progress_given(first_error.map(|d| d.to_string()))
|
||||
}
|
||||
|
||||
/// The checklist, given the model check's first error (`model.check` has run it already).
|
||||
pub(crate) fn progress_given(&self, first_error: Option<String>) -> Vec<StageState> {
|
||||
let m = &self.model;
|
||||
let analysable = Requirement::Analysable.met(self);
|
||||
// Models without elements (point masses, fluid domains) need no material or section.
|
||||
let elementless = analysable && m.elements().is_empty();
|
||||
let modal_only = !m.steps().is_empty() && m.steps().iter().all(|st| matches!(st.procedure, Procedure::Frequency { .. }));
|
||||
let mut next_given = false;
|
||||
Stage::ALL
|
||||
.into_iter()
|
||||
.map(|stage| {
|
||||
let r = stage.requirement();
|
||||
let done = r.met(self) || (stage == Stage::Geometry && analysable);
|
||||
let optional = match stage {
|
||||
Stage::Prepare => true,
|
||||
Stage::Material | Stage::Section => elementless,
|
||||
Stage::Loads => modal_only,
|
||||
_ => false,
|
||||
};
|
||||
let command = r.provider();
|
||||
let blocked = match crate::find_command(command).map(|spec| self.availability(spec)) {
|
||||
Some(Err(u)) => Some(u.lines()),
|
||||
_ if stage == Stage::Solve => first_error.clone(),
|
||||
_ => None,
|
||||
};
|
||||
let (status, detail) = if done {
|
||||
(Status::Done, None)
|
||||
} else if optional {
|
||||
(Status::Optional, None)
|
||||
} else if blocked.is_some() {
|
||||
next_given = true;
|
||||
(Status::Blocked, blocked)
|
||||
} else if next_given {
|
||||
(Status::Todo, None)
|
||||
} else {
|
||||
next_given = true;
|
||||
(Status::Next, None)
|
||||
};
|
||||
StageState { stage, label: stage.label(), status, command, place: r.place(), detail }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// The checklist as JSON, with the next stage's command first for agents:
|
||||
/// `{"next": {"stage", "command"} | null, "stages": [...]}`.
|
||||
pub fn to_json(stages: &[StageState]) -> Value {
|
||||
let next = stages.iter().find(|s| matches!(s.status, Status::Next | Status::Blocked));
|
||||
json!({
|
||||
"next": next.map(|s| json!({"stage": s.stage, "command": s.command, "status": s.status, "detail": s.detail})),
|
||||
"stages": stages,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use Status::*;
|
||||
|
||||
fn statuses(s: &Session) -> Vec<(Stage, Status)> {
|
||||
s.progress().into_iter().map(|st| (st.stage, st.status)).collect()
|
||||
}
|
||||
|
||||
fn status(s: &Session, stage: Stage) -> Status {
|
||||
statuses(s).into_iter().find(|(st, _)| *st == stage).map(|(_, st)| st).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_model_starts_with_geometry() {
|
||||
let s = Session::default();
|
||||
let p = s.progress();
|
||||
assert_eq!(p.len(), Stage::ALL.len());
|
||||
assert_eq!((p[0].stage, p[0].status, p[0].command), (Stage::Geometry, Next, "geometry.open"));
|
||||
assert_eq!(status(&s, Stage::Prepare), Optional);
|
||||
// Meshing needs geometry; solving needs a mesh.
|
||||
assert_eq!(status(&s, Stage::Mesh), Blocked);
|
||||
assert!(p[2].detail.as_deref().is_some_and(|d| d.contains("geometry")));
|
||||
assert_eq!(status(&s, Stage::Material), Todo);
|
||||
assert_eq!(status(&s, Stage::Solve), Blocked);
|
||||
assert_eq!(statuses(&s).iter().filter(|(_, st)| *st == Next).count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_meshed_model_asks_for_its_material_next() {
|
||||
let mut s = Session::default();
|
||||
let cube = [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0], [0, 0, 1], [1, 0, 1], [1, 1, 1], [0, 1, 1]];
|
||||
s.execute("mesh.block", &json!({"body": "B", "kind": "hex8", "corners": cube, "divisions": [1, 1, 1]})).unwrap();
|
||||
assert_eq!(status(&s, Stage::Geometry), Done);
|
||||
assert_eq!(status(&s, Stage::Mesh), Done);
|
||||
assert_eq!(status(&s, Stage::Material), Next);
|
||||
assert_eq!(status(&s, Stage::Section), Blocked);
|
||||
assert_eq!(status(&s, Stage::Step), Todo);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_defined_model_is_ready_to_solve_then_to_show_results() {
|
||||
let mut s = Session::default();
|
||||
crate::cmd::solve::tests::cantilever(&mut s);
|
||||
let before = statuses(&s);
|
||||
for (stage, st) in &before[..9] {
|
||||
assert!(matches!(st, Done | Optional), "{stage:?} {st:?}");
|
||||
}
|
||||
assert_eq!(status(&s, Stage::Solve), Next);
|
||||
assert_eq!(to_json(&s.progress())["next"]["command"], "solve.run");
|
||||
s.execute("solve.run", &json!({})).unwrap();
|
||||
// A solve shows its results.
|
||||
assert!(statuses(&s).iter().all(|(_, st)| matches!(st, Done | Optional)));
|
||||
assert!(to_json(&s.progress())["next"].is_null());
|
||||
s.execute("results.clear", &json!({})).unwrap();
|
||||
assert_eq!(status(&s, Stage::Solve), Done);
|
||||
assert_eq!((status(&s, Stage::Results), to_json(&s.progress())["next"]["command"].clone()), (Next, json!("results.contour")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_check_returns_the_checklist() {
|
||||
let mut s = Session::default();
|
||||
let v = s.execute("model.check", &json!({})).unwrap();
|
||||
assert_eq!(v["progress"]["next"]["command"], "geometry.open");
|
||||
assert_eq!(v["progress"]["stages"].as_array().map(Vec::len), Some(Stage::ALL.len()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,391 @@
|
||||
//! What a command needs in the session before it can run: its [`Requirement`]s.
|
||||
//!
|
||||
//! Each [`crate::CommandSpec`] lists its requirements (`requires`) next to its id. A requirement
|
||||
//! is something the command cannot run without — an open design to mesh, a material to give
|
||||
//! plasticity to, a result to contour — never a workflow order: a script that builds a model step
|
||||
//! by step meets each command's requirements as it goes.
|
||||
//!
|
||||
//! [`Session::execute`] checks them before running a command, so a command whose requirement is
|
||||
//! missing fails at once, with no partial work, naming each missing piece and the toolbar entry
|
||||
//! that provides it ([`Unavailable`]). The desktop UI reads the same check
|
||||
//! ([`Session::availability`]) to grey the ribbon buttons, the command search and Solve, with the
|
||||
//! same text as their tooltip. Every check is a count or a few comparisons, cheap enough to run
|
||||
//! for every button on every frame.
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::{CommandSpec, Session, catalogue};
|
||||
|
||||
/// Something a command needs in the session.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Requirement {
|
||||
/// An open SolidCraft design (`geometry.open`).
|
||||
Design,
|
||||
/// Geometry to mesh: an open design or an imported surface.
|
||||
Geometry,
|
||||
/// A datum plane, axis or point.
|
||||
Datum,
|
||||
/// A datum plane (what a partition cuts by).
|
||||
DatumPlane,
|
||||
DatumAxis,
|
||||
DatumPoint,
|
||||
/// A partition of the design.
|
||||
Partition,
|
||||
/// An edge seed.
|
||||
Seed,
|
||||
/// At least one mesh node.
|
||||
Nodes,
|
||||
/// At least one element.
|
||||
Mesh,
|
||||
/// Something to analyse: elements, point masses or springs, or only fluid steps (whose
|
||||
/// domains carry their own grid) — the model check's first rule.
|
||||
Analysable,
|
||||
/// A material for the elements: met when there is a material or no element.
|
||||
ElementMaterial,
|
||||
/// A section for the elements: met when there is a section or no element.
|
||||
ElementSection,
|
||||
Set,
|
||||
/// A set or a reference point (what boundary conditions, masses and springs act on).
|
||||
Target,
|
||||
Material,
|
||||
Section,
|
||||
ReferencePoint,
|
||||
Coupling,
|
||||
Contact,
|
||||
Tie,
|
||||
Mass,
|
||||
Spring,
|
||||
BoundaryCondition,
|
||||
Load,
|
||||
FluidDomain,
|
||||
Step,
|
||||
/// A solved step's result (current or stale).
|
||||
Result,
|
||||
/// Results on the display.
|
||||
ResultsShown,
|
||||
}
|
||||
|
||||
impl Requirement {
|
||||
/// Whether the session meets it.
|
||||
pub fn met(self, s: &Session) -> bool {
|
||||
let m = &s.model;
|
||||
let has_elements = !m.elements().is_empty();
|
||||
match self {
|
||||
Requirement::Design => s.design.is_some(),
|
||||
Requirement::Geometry => s.design.is_some() || !s.surfaces.is_empty(),
|
||||
Requirement::Datum => !m.datums().is_empty(),
|
||||
Requirement::DatumPlane => m.datums().values().any(|d| d.plane().is_some()),
|
||||
Requirement::DatumAxis => m.datums().values().any(|d| d.axis().is_some()),
|
||||
Requirement::DatumPoint => m.datums().values().any(|d| d.point().is_some()),
|
||||
Requirement::Partition => !m.partitions().is_empty(),
|
||||
Requirement::Seed => !m.seeds().is_empty(),
|
||||
Requirement::Nodes => !m.nodes().is_empty(),
|
||||
Requirement::Mesh => has_elements,
|
||||
Requirement::Analysable => {
|
||||
has_elements
|
||||
|| !m.masses().is_empty()
|
||||
|| !m.springs().is_empty()
|
||||
|| (!m.steps().is_empty() && m.steps().iter().all(|st| st.procedure.fluid_domain().is_some()))
|
||||
}
|
||||
Requirement::ElementMaterial => !has_elements || !m.materials().is_empty(),
|
||||
Requirement::ElementSection => !has_elements || !m.sections().is_empty(),
|
||||
Requirement::Set => !m.sets().is_empty(),
|
||||
Requirement::Target => !m.sets().is_empty() || !m.reference_points().is_empty(),
|
||||
Requirement::Material => !m.materials().is_empty(),
|
||||
Requirement::Section => !m.sections().is_empty(),
|
||||
Requirement::ReferencePoint => !m.reference_points().is_empty(),
|
||||
Requirement::Coupling => !m.couplings().is_empty(),
|
||||
Requirement::Contact => !m.contacts().is_empty(),
|
||||
Requirement::Tie => !m.ties().is_empty(),
|
||||
Requirement::Mass => !m.masses().is_empty(),
|
||||
Requirement::Spring => !m.springs().is_empty(),
|
||||
Requirement::BoundaryCondition => !m.boundary_conditions().is_empty(),
|
||||
Requirement::Load => !m.loads().is_empty(),
|
||||
Requirement::FluidDomain => !m.fluid_domains().is_empty(),
|
||||
Requirement::Step => !m.steps().is_empty(),
|
||||
Requirement::Result => s.result_steps().next().is_some(),
|
||||
Requirement::ResultsShown => s.results_view.is_some(),
|
||||
}
|
||||
}
|
||||
|
||||
/// What is missing, as a noun phrase ("a material").
|
||||
pub fn what(self) -> &'static str {
|
||||
match self {
|
||||
Requirement::Design => "an open design",
|
||||
Requirement::Geometry => "geometry (an open design or an imported surface)",
|
||||
Requirement::Datum => "a datum",
|
||||
Requirement::DatumPlane => "a datum plane",
|
||||
Requirement::DatumAxis => "a datum axis",
|
||||
Requirement::DatumPoint => "a datum point",
|
||||
Requirement::Partition => "a partition",
|
||||
Requirement::Seed => "an edge seed",
|
||||
Requirement::Nodes => "mesh nodes",
|
||||
Requirement::Mesh | Requirement::Analysable => "a mesh",
|
||||
Requirement::ElementMaterial | Requirement::Material => "a material",
|
||||
Requirement::ElementSection | Requirement::Section => "a section",
|
||||
Requirement::Set => "a set",
|
||||
Requirement::Target => "a set or a reference point",
|
||||
Requirement::ReferencePoint => "a reference point",
|
||||
Requirement::Coupling => "a coupling",
|
||||
Requirement::Contact => "a contact",
|
||||
Requirement::Tie => "a tie",
|
||||
Requirement::Mass => "a point mass",
|
||||
Requirement::Spring => "a spring or dashpot",
|
||||
Requirement::BoundaryCondition => "a boundary condition",
|
||||
Requirement::Load => "a load",
|
||||
Requirement::FluidDomain => "a fluid domain",
|
||||
Requirement::Step => "a step",
|
||||
Requirement::Result => "a solved step",
|
||||
Requirement::ResultsShown => "results on the display",
|
||||
}
|
||||
}
|
||||
|
||||
/// The command that provides it.
|
||||
pub fn provider(self) -> &'static str {
|
||||
match self {
|
||||
Requirement::Design | Requirement::Geometry => "geometry.open",
|
||||
Requirement::Datum | Requirement::DatumPlane => "geometry.datum",
|
||||
Requirement::DatumAxis => "geometry.datum.axis",
|
||||
Requirement::DatumPoint => "geometry.datum.point",
|
||||
Requirement::Partition => "geometry.partition",
|
||||
Requirement::Seed => "mesh.seed.edge",
|
||||
Requirement::Nodes => "mesh.node.add",
|
||||
Requirement::Mesh | Requirement::Analysable => "mesh.tet.generate",
|
||||
Requirement::ElementMaterial | Requirement::Material => "model.material.create",
|
||||
Requirement::ElementSection | Requirement::Section => "model.section.create",
|
||||
Requirement::Set | Requirement::Target => "model.set.create",
|
||||
Requirement::ReferencePoint => "model.reference_point.create",
|
||||
Requirement::Coupling => "model.coupling.create",
|
||||
Requirement::Contact => "interaction.contact.pair",
|
||||
Requirement::Tie => "interaction.tie",
|
||||
Requirement::Mass => "model.mass.create",
|
||||
Requirement::Spring => "model.spring.create",
|
||||
Requirement::BoundaryCondition => "model.boundary_condition.create",
|
||||
Requirement::Load => "model.load.create",
|
||||
Requirement::FluidDomain => "model.fluid_domain.create",
|
||||
Requirement::Step => "model.step.create",
|
||||
Requirement::Result => "solve.run",
|
||||
Requirement::ResultsShown => "results.contour",
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the provider is on the toolbar: "Properties › Material".
|
||||
pub fn place(self) -> String {
|
||||
let id = self.provider();
|
||||
match catalogue::entry_of(id) {
|
||||
Some(c) => format!("{} › {}", c.tab.label(), c.label),
|
||||
None => id.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::schema::Collection {
|
||||
/// What an item of the collection is as a requirement: its [`Requirement::provider`] is the
|
||||
/// command that makes one, which a form offers when a reference field has nothing to pick.
|
||||
pub fn requirement(self) -> Requirement {
|
||||
use crate::schema::Collection as C;
|
||||
match self {
|
||||
C::Set => Requirement::Set,
|
||||
C::Material => Requirement::Material,
|
||||
C::Section => Requirement::Section,
|
||||
C::ReferencePoint => Requirement::ReferencePoint,
|
||||
C::Coupling => Requirement::Coupling,
|
||||
C::Contact => Requirement::Contact,
|
||||
C::Tie => Requirement::Tie,
|
||||
C::Mass => Requirement::Mass,
|
||||
C::Spring => Requirement::Spring,
|
||||
C::BoundaryCondition => Requirement::BoundaryCondition,
|
||||
C::Load => Requirement::Load,
|
||||
C::FluidDomain => Requirement::FluidDomain,
|
||||
C::Step => Requirement::Step,
|
||||
C::SolvedStep => Requirement::Result,
|
||||
C::Body => Requirement::Design,
|
||||
C::Datum => Requirement::Datum,
|
||||
C::DatumPlane => Requirement::DatumPlane,
|
||||
C::DatumAxis => Requirement::DatumAxis,
|
||||
C::DatumPoint => Requirement::DatumPoint,
|
||||
C::Partition => Requirement::Partition,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A requirement the session does not meet.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Missing(pub Requirement);
|
||||
|
||||
impl std::fmt::Display for Missing {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "Needs {} — {}", self.0.what(), self.0.place())
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a command cannot run now: every requirement it misses, in its spec's order.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Unavailable {
|
||||
pub command: &'static str,
|
||||
pub missing: Vec<Missing>,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Unavailable {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{} cannot run yet. {}", self.command, self.joined("; "))
|
||||
}
|
||||
}
|
||||
|
||||
impl Unavailable {
|
||||
fn joined(&self, separator: &str) -> String {
|
||||
self.missing.iter().map(ToString::to_string).collect::<Vec<_>>().join(separator)
|
||||
}
|
||||
|
||||
/// The missing pieces, one per line.
|
||||
pub fn lines(&self) -> String {
|
||||
self.joined("\n")
|
||||
}
|
||||
|
||||
/// A hover text: `head`, then the missing pieces when there are any.
|
||||
pub fn tip(head: &str, missing: Option<&Unavailable>) -> String {
|
||||
match missing {
|
||||
Some(u) => format!("{head}\n\n{}", u.lines()),
|
||||
None => head.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// As JSON for the control channel and listings: `{"reason", "missing": [{"requirement",
|
||||
/// "what", "provider", "place"}]}`.
|
||||
pub fn to_json(&self) -> serde_json::Value {
|
||||
let missing: Vec<serde_json::Value> = self
|
||||
.missing
|
||||
.iter()
|
||||
.map(|Missing(r)| serde_json::json!({"requirement": r, "what": r.what(), "provider": r.provider(), "place": r.place()}))
|
||||
.collect();
|
||||
serde_json::json!({"reason": self.lines(), "missing": missing})
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Whether `spec` can run now: `Err` names every requirement it misses.
|
||||
pub fn availability(&self, spec: &CommandSpec) -> std::result::Result<(), Unavailable> {
|
||||
let missing: Vec<Missing> = spec.requires.iter().filter(|r| !r.met(self)).map(|&r| Missing(r)).collect();
|
||||
if missing.is_empty() { Ok(()) } else { Err(Unavailable { command: spec.id, missing }) }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{EngineError, commands};
|
||||
use serde_json::json;
|
||||
|
||||
fn missing(s: &Session, id: &str) -> Vec<Requirement> {
|
||||
let spec = crate::find_command(id).unwrap();
|
||||
s.availability(spec).err().map(|u| u.missing.into_iter().map(|Missing(r)| r).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Every command in an empty session is either available or names what it misses, with the
|
||||
/// toolbar entry that provides it; and running one that misses something fails at once with
|
||||
/// that same message, leaving the session as it was.
|
||||
#[test]
|
||||
fn every_command_in_an_empty_session_runs_or_names_what_it_misses() {
|
||||
for spec in commands() {
|
||||
let mut s = Session::default();
|
||||
match s.availability(spec) {
|
||||
Ok(()) => {}
|
||||
Err(u) => {
|
||||
assert!(!u.missing.is_empty(), "{}", spec.id);
|
||||
for Missing(r) in &u.missing {
|
||||
assert!(crate::find_command(r.provider()).is_some(), "{}: {r:?}", spec.id);
|
||||
assert!(catalogue::entry_of(r.provider()).is_some(), "{}: {r:?} has no toolbar entry", spec.id);
|
||||
assert!(!r.met(&s));
|
||||
}
|
||||
let journal = s.journal.len();
|
||||
let e = s.execute(spec.id, &json!({})).unwrap_err();
|
||||
assert_eq!(e, EngineError::Unavailable(u.clone()), "{}", spec.id);
|
||||
assert!(e.to_string().contains("Needs "), "{e}");
|
||||
assert_eq!(s.journal.len(), journal);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Each provider meets what it provides on its own: a requirement is never one its provider
|
||||
/// itself cannot meet from an empty model (no circular greying).
|
||||
#[test]
|
||||
fn providers_are_not_greyed_by_what_they_provide() {
|
||||
for spec in commands() {
|
||||
for r in spec.requires {
|
||||
let provider = crate::find_command(r.provider()).unwrap();
|
||||
assert!(!provider.requires.contains(r), "{} provides {r:?} but requires it", provider.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A collection's requirement is met exactly when it has a name to pick, and its provider is
|
||||
/// a command on the toolbar.
|
||||
#[test]
|
||||
fn collections_require_what_they_list() {
|
||||
use crate::schema::Collection as C;
|
||||
let all = [
|
||||
C::Set,
|
||||
C::Material,
|
||||
C::Section,
|
||||
C::ReferencePoint,
|
||||
C::Coupling,
|
||||
C::Contact,
|
||||
C::Tie,
|
||||
C::Mass,
|
||||
C::Spring,
|
||||
C::BoundaryCondition,
|
||||
C::Load,
|
||||
C::FluidDomain,
|
||||
C::Step,
|
||||
C::SolvedStep,
|
||||
C::Body,
|
||||
C::Datum,
|
||||
C::DatumPlane,
|
||||
C::DatumAxis,
|
||||
C::DatumPoint,
|
||||
C::Partition,
|
||||
];
|
||||
let empty = Session::default();
|
||||
for c in all {
|
||||
let r = c.requirement();
|
||||
assert!(empty.names(c).is_empty() && !r.met(&empty), "{c:?}");
|
||||
assert!(catalogue::entry_of(r.provider()).is_some(), "{c:?}");
|
||||
}
|
||||
let mut s = Session::default();
|
||||
s.execute("model.material.create", &json!({"name": "Steel", "elastic": {"type": "isotropic", "young": 210000, "poisson": 0.3}})).unwrap();
|
||||
assert!(C::Material.requirement().met(&s) && s.names(C::Material) == ["Steel"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn targeted_requirements() {
|
||||
let empty = Session::default();
|
||||
assert_eq!(missing(&empty, "model.material.plasticity"), [Requirement::Material]);
|
||||
assert_eq!(missing(&empty, "results.contour"), [Requirement::Result]);
|
||||
assert_eq!(missing(&empty, "solve.static"), [Requirement::Analysable, Requirement::Step]);
|
||||
assert_eq!(missing(&empty, "mesh.tet.generate"), [Requirement::Geometry]);
|
||||
assert!(missing(&empty, "model.material.create").is_empty());
|
||||
assert!(missing(&empty, "model.step.create").is_empty());
|
||||
|
||||
// Meshed, nothing defined: solving needs a material, a section and a step.
|
||||
let mut meshed = Session::default();
|
||||
let cube = [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0], [0, 0, 1], [1, 0, 1], [1, 1, 1], [0, 1, 1]];
|
||||
meshed.execute("mesh.block", &json!({"body": "B", "kind": "hex8", "corners": cube, "divisions": [1, 1, 1]})).unwrap();
|
||||
assert_eq!(missing(&meshed, "solve.static"), [Requirement::ElementMaterial, Requirement::ElementSection, Requirement::Step]);
|
||||
let e = meshed.execute("solve.run", &json!({})).unwrap_err().to_string();
|
||||
assert_eq!(
|
||||
e,
|
||||
"solve.run cannot run yet. Needs a material — Properties › Material; Needs a section — Properties › Section; Needs a step — Steps › Step"
|
||||
);
|
||||
|
||||
// A defined, solved cantilever: everything a result needs is there.
|
||||
let mut solved = Session::default();
|
||||
crate::cmd::solve::tests::cantilever(&mut solved);
|
||||
assert!(missing(&solved, "solve.run").is_empty());
|
||||
solved.execute("solve.run", &json!({})).unwrap();
|
||||
for id in ["results.contour", "results.deformed", "solve.probe", "results.clear", "model.material.plasticity"] {
|
||||
assert!(missing(&solved, id).is_empty(), "{id}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -268,9 +268,11 @@ pub struct ResultsView {
|
||||
}
|
||||
|
||||
impl ResultsView {
|
||||
/// How a step's result is shown first: deformed, with von Mises contours for a static step
|
||||
/// (and an explicit step that kept stresses), the first mode with displacement contours for
|
||||
/// a frequency step; an explicit step at its last frame, to true scale.
|
||||
/// How a step's result is shown first: a static step undeformed with von Mises contours, so
|
||||
/// they are read on the true geometry (`results.deformed` shows the deformed shape, at the
|
||||
/// automatic scale); a frequency step's first mode deformed with displacement contours (a
|
||||
/// mode shape is a deformation); an explicit step at its last frame, deformed to true scale
|
||||
/// (with von Mises contours when it kept stresses); a heat step undeformed.
|
||||
pub fn for_result(r: &StepResult) -> ResultsView {
|
||||
let heat = matches!(r.kind(), Kind::Heat(_));
|
||||
let contour = if heat {
|
||||
@@ -283,7 +285,7 @@ impl ResultsView {
|
||||
let scale = matches!(r.kind(), Kind::Explicit(_)).then_some(1.0);
|
||||
ResultsView {
|
||||
step: r.step().to_string(),
|
||||
deformed: !heat,
|
||||
deformed: matches!(r.kind(), Kind::Frequency(_) | Kind::Explicit(_)),
|
||||
scale,
|
||||
contour: Some(contour),
|
||||
bands: DEFAULT_BANDS,
|
||||
|
||||
@@ -27,6 +27,9 @@ pub struct Sample {
|
||||
/// The SolidCraft script (`{"commands": [...]}`, the corpus recipe form) that builds the
|
||||
/// sample's geometry, opened as its design before [`Sample::script`] runs.
|
||||
pub design: Option<&'static str>,
|
||||
/// Commands run on the opened design before [`Sample::script`] (datums and partitions), so
|
||||
/// the script is given the bodies as they cut it.
|
||||
pub prepare: Option<fn() -> Value>,
|
||||
/// The model's commands, given the design's bodies (none without a design).
|
||||
pub script: fn(&[Shape]) -> Value,
|
||||
}
|
||||
@@ -38,6 +41,7 @@ pub const SAMPLES: &[Sample] = &[
|
||||
label: "Hex and Tet Parts",
|
||||
about: "A hex8 block beside a tet4 cube: meshes to look at, nothing to solve",
|
||||
design: None,
|
||||
prepare: None,
|
||||
script: |_| script(),
|
||||
},
|
||||
Sample {
|
||||
@@ -45,6 +49,7 @@ pub const SAMPLES: &[Sample] = &[
|
||||
label: "Cantilever",
|
||||
about: "A clamped steel beam with an end load: a static and a frequency step, ready to solve",
|
||||
design: None,
|
||||
prepare: None,
|
||||
script: |_| cantilever(),
|
||||
},
|
||||
Sample {
|
||||
@@ -52,6 +57,7 @@ pub const SAMPLES: &[Sample] = &[
|
||||
label: "Bar Impact",
|
||||
about: "The steel beam flying onto a rigid wall: an explicit dynamic step, ready to solve",
|
||||
design: None,
|
||||
prepare: None,
|
||||
script: |_| impact(),
|
||||
},
|
||||
Sample {
|
||||
@@ -59,6 +65,7 @@ pub const SAMPLES: &[Sample] = &[
|
||||
label: "Drop Test",
|
||||
about: "An aluminium L-bracket dropped 2 m onto a tilted rigid floor: explicit dynamics, the strike and its stress waves",
|
||||
design: Some(UPRIGHT_BRACKET),
|
||||
prepare: None,
|
||||
script: |_| drop_test(),
|
||||
},
|
||||
Sample {
|
||||
@@ -66,6 +73,7 @@ pub const SAMPLES: &[Sample] = &[
|
||||
label: "Rubber Seal",
|
||||
about: "A rubber gasket ring squeezed 25 % between bonded plates: nonlinear static, Mooney–Rivlin, large strain",
|
||||
design: None,
|
||||
prepare: None,
|
||||
script: |_| rubber_seal(),
|
||||
},
|
||||
Sample {
|
||||
@@ -73,6 +81,7 @@ pub const SAMPLES: &[Sample] = &[
|
||||
label: "Flow Past a Bracket",
|
||||
about: "Air flowing past an L-bracket on the floor: lattice Boltzmann flow and the force on each face",
|
||||
design: Some(UPRIGHT_BRACKET),
|
||||
prepare: None,
|
||||
script: |_| flow_past(),
|
||||
},
|
||||
Sample {
|
||||
@@ -80,6 +89,7 @@ pub const SAMPLES: &[Sample] = &[
|
||||
label: "Heated Bracket",
|
||||
about: "A steel bracket clamped at its holes and heated at one end: steady heat conduction and the thermal stress",
|
||||
design: Some(FILLETED_BRACKET),
|
||||
prepare: None,
|
||||
script: |_| heated_bracket(),
|
||||
},
|
||||
Sample {
|
||||
@@ -87,13 +97,23 @@ pub const SAMPLES: &[Sample] = &[
|
||||
label: "Hex-Meshed Bracket",
|
||||
about: "The filleted bracket split into 30 cells and meshed all-hex (hex20): clamped, loaded, von Mises",
|
||||
design: Some(PARTITIONED_BRACKET),
|
||||
prepare: None,
|
||||
script: bracket_hex,
|
||||
},
|
||||
Sample {
|
||||
name: "crank-mirror",
|
||||
label: "Mirrored Crank Arm",
|
||||
about: "The crank arm of crank-arm under the name of its mirror workflow: a partitioned half meshed structured all-hex (hex20) and mirrored into one conforming mesh",
|
||||
design: Some(CRANK_ARM),
|
||||
prepare: Some(crank_prepare),
|
||||
script: crank_arm,
|
||||
},
|
||||
Sample {
|
||||
name: "crank-arm",
|
||||
label: "Bicycle Crank Arm",
|
||||
about: "An aluminium bicycle crank swept all-hex (hex20): square bore fixed, a rider's weight on the pedal, von Mises",
|
||||
about: "An aluminium bicycle crank meshed structured all-hex (hex20) from a partitioned half and its mirror image: square bore fixed, a rider's weight on the pedal, von Mises",
|
||||
design: Some(CRANK_ARM),
|
||||
prepare: Some(crank_prepare),
|
||||
script: crank_arm,
|
||||
},
|
||||
];
|
||||
@@ -477,17 +497,45 @@ pub const CRANK_ARM: &str = include_str!("../samples/crank-arm.json");
|
||||
/// The crank arm's pedal load (N): a standing rider's weight on one pedal.
|
||||
pub const PEDAL_LOAD: f64 = 1500.0;
|
||||
|
||||
/// [`CRANK_ARM`] swept all-hex (hex20 of 3 mm), in 6061-T6 aluminium: the square bore's faces
|
||||
/// and corner fillets (set `spindle`) fixed, [`PEDAL_LOAD`] on the pedal hole (set `pedal`), in
|
||||
/// the crank's plane and across the arm (−y). Step `Pedal` (linear static). The faces are picked
|
||||
/// by their surfaces, not their names: the square bore's are the vertical planes 6.35 mm from the
|
||||
/// spindle axis and the R1.5 cylinders beside it, the pedal hole is the Ø14 cylinder on the
|
||||
/// pedal axis.
|
||||
/// The half of the crank [`crank_prepare`] cuts off on the symmetry plane (y < 0), the one
|
||||
/// meshed; its mirror image is `CrankArm/b`.
|
||||
pub const CRANK_HALF: &str = "CrankArm/a";
|
||||
|
||||
/// [`CRANK_ARM`] meshed structured all-hex (hex20 of 3 mm) from its half and mirrored, in
|
||||
/// 6061-T6 aluminium: the square bore's faces and corner fillets (set `spindle`) fixed,
|
||||
/// [`PEDAL_LOAD`] on the pedal hole (set `pedal`), in the crank's plane and across the arm (−y).
|
||||
/// Step `Pedal` (linear static). The faces are picked by their surfaces, not their names: the
|
||||
/// square bore's are the vertical planes 6.35 mm from the spindle axis and the R1.5 cylinders
|
||||
/// beside it, the pedal hole is the Ø14 cylinder on the pedal axis.
|
||||
///
|
||||
/// The mesh: [`crank_prepare`] cuts the crank on its symmetry plane only; `mesh.hex.generate`
|
||||
/// extrudes the half [`CRANK_HALF`], decomposing its cross-section into blocks itself (half
|
||||
/// rings round both bores, the pocket's corners as triangle primitives, four-sided blocks along
|
||||
/// the arm), with no seeds; `mesh.mirror` reflects it onto `CrankArm/b`, joined on the plane.
|
||||
pub fn crank_arm(bodies: &[Shape]) -> Value {
|
||||
let [spindle, pedal] = crank_faces(bodies);
|
||||
let mesh = vec![
|
||||
json!({"command": "mesh.hex.generate", "params": {"body": CRANK_HALF, "method": "extrude", "size": 3, "order": 2}}),
|
||||
json!({"command": "mesh.mirror", "params": {"plane": "Sym", "bodies": [CRANK_HALF], "as": {CRANK_HALF: "CrankArm/b"}}}),
|
||||
];
|
||||
crank_model(bodies, mesh)
|
||||
}
|
||||
|
||||
/// The crank arm's symmetry plane (`Sym`, y = 0) and the partition by it (`Half`): the one datum
|
||||
/// the structured mesh needs.
|
||||
fn crank_prepare() -> Value {
|
||||
json!([
|
||||
{"command": "model.units", "params": {"system": "mm-t-s-N-MPa"}},
|
||||
{"command": "mesh.hex.generate", "params": {"size": 3, "order": 2, "method": "extrude"}},
|
||||
{"command": "geometry.datum", "params": {"name": "Sym", "by": {"type": "offset", "plane": "zx", "offset": 0}}},
|
||||
{"command": "geometry.partition", "params": {"name": "Half", "datum": "Sym"}},
|
||||
])
|
||||
}
|
||||
|
||||
/// The crank's model after the `mesh` commands: material, the spindle fixed, the rider on the
|
||||
/// pedal, step `Pedal`.
|
||||
fn crank_model(bodies: &[Shape], mesh: Vec<Value>) -> Value {
|
||||
let [spindle, pedal] = crank_faces(bodies);
|
||||
let mut script = vec![json!({"command": "model.units", "params": {"system": "mm-t-s-N-MPa"}})];
|
||||
script.extend(mesh);
|
||||
script.extend(json_array(json!([
|
||||
{"command": "model.set.create", "params": {"name": "crank", "geometry": bodies.iter().map(|b| json!({"body": b.name})).collect::<Vec<_>>()}},
|
||||
{"command": "model.set.create", "params": {"name": "spindle", "geometry": spindle}},
|
||||
{"command": "model.set.create", "params": {"name": "pedal", "geometry": pedal}},
|
||||
@@ -496,7 +544,15 @@ pub fn crank_arm(bodies: &[Shape]) -> Value {
|
||||
{"command": "model.boundary_condition.create", "params": {"name": "Spindle", "type": "fixed", "target": {"set": "spindle"}}},
|
||||
{"command": "model.load.create", "params": {"name": "Rider", "type": "force", "target": {"set": "pedal"}, "vector": [0, -PEDAL_LOAD, 0]}},
|
||||
{"command": "model.step.create", "params": {"name": "Pedal", "procedure": {"type": "static"}, "boundary_conditions": ["Spindle"], "loads": ["Rider"]}},
|
||||
])
|
||||
])));
|
||||
Value::Array(script)
|
||||
}
|
||||
|
||||
fn json_array(v: Value) -> Vec<Value> {
|
||||
match v {
|
||||
Value::Array(a) => a,
|
||||
other => vec![other],
|
||||
}
|
||||
}
|
||||
|
||||
/// The crank's square-bore faces and pedal-hole faces as set members, found by their surfaces.
|
||||
@@ -685,12 +741,25 @@ mod tests {
|
||||
assert!(r["mass"]["relative_change"].as_f64().unwrap().abs() < 0.01, "{r}");
|
||||
}
|
||||
|
||||
/// The heated bracket's 4 mm tet mesh stays near its 23 000 elements. #303: refinement piled
|
||||
/// face vertices against a feature curve, and the improvement then grew the mesh to 29 257
|
||||
/// elements in about two minutes. The element count is the check: wall time depends on the
|
||||
/// machine and the build profile (about 5 s in a release build, far longer on CI).
|
||||
#[test]
|
||||
#[ignore = "heavy: cargo xtask test --heavy (CI heavy job)"]
|
||||
fn the_heated_bracket_opens_with_its_usual_mesh() {
|
||||
let s = open("heated-bracket");
|
||||
let elements = s.model.elements().len();
|
||||
assert!((20_000..=26_000).contains(&elements), "{elements} elements");
|
||||
}
|
||||
|
||||
/// The heated bracket's temperatures lie between the air's and the heater's, falling along
|
||||
/// the bracket away from the heater. Its thermal expansion: with the air at the heater's
|
||||
/// temperature the bracket warms evenly by ΔT, and held at the foot's hole alone (at x = 40)
|
||||
/// it grows freely, so a point moves α ΔT times its distance from the hole's axis along x:
|
||||
/// the upright's top by −0.0432 mm (within 2 %), the foot's end by +0.024 mm (within 6 %:
|
||||
/// the clamped bore cannot grow).
|
||||
/// the upright's top by −0.0432 mm (within 3 %), the foot's end by +0.024 mm (within 6 %).
|
||||
/// The clamped bore cannot grow, which holds both points back a little; how much depends on
|
||||
/// the tet mesh, which differs between platforms (#115): 2.1 % at the top on the Linux CI.
|
||||
#[test]
|
||||
#[ignore = "heavy: cargo xtask test --heavy (CI heavy job)"]
|
||||
fn the_heated_bracket_warms_and_expands_as_steel() {
|
||||
@@ -711,7 +780,7 @@ mod tests {
|
||||
let grow = STEEL_EXPANSION * (HEATER - AMBIENT);
|
||||
// The bore itself cannot grow, which holds back the foot's end, 16 mm from its edge, a
|
||||
// little more than the upright's top, 32 mm away.
|
||||
for (i, tolerance) in [(0, 0.02), (1, 0.06)] {
|
||||
for (i, tolerance) in [(0, 0.03), (1, 0.06)] {
|
||||
let node = &p["nodes"][i];
|
||||
let (ux, expected) = (node["displacement"][0].as_f64().unwrap(), grow * (node["xyz"][0].as_f64().unwrap() - 40.0));
|
||||
assert!((ux - expected).abs() < tolerance * expected.abs(), "{node}: {ux} against {expected}");
|
||||
@@ -737,18 +806,66 @@ mod tests {
|
||||
assert!(r["max_von_mises"]["value"].as_f64().unwrap() > 200.0, "{r}");
|
||||
}
|
||||
|
||||
/// The crank arm opens swept all-hex20 with every bore face found, and its root bends as a
|
||||
/// beam: σxx on the arm's sides at x = 29 mm (35.6 mm wide, 16 thick, 141 mm from the pedal)
|
||||
/// within 3 % of M/Z = 1500 · 141 / (16 · 35.6² / 6) = 62.6 MPa, the spindle carrying the
|
||||
/// The crank opens as one conforming structured hex20 mesh: the half meshed in blocks
|
||||
/// without partitions or seeds, no ties, the half and its mirror
|
||||
/// image alike and joined on the symmetry plane, the spindle and pedal faces found on both
|
||||
/// halves (the image's faces carry the names of the half they are the image of), and the
|
||||
/// quality floor: scaled Jacobian at least 0.37, edge ratio at most 10.
|
||||
#[test]
|
||||
fn the_crank_opens_as_one_structured_mesh_of_two_alike_halves() {
|
||||
let (arm, mirror) = (find("crank-arm").unwrap(), find("crank-mirror").unwrap());
|
||||
let prepared = |x: &Sample| x.prepare.map(|f| f());
|
||||
assert!(
|
||||
arm.design == mirror.design && prepared(arm) == prepared(mirror) && (arm.script)(&[]) == (mirror.script)(&[]),
|
||||
"one model under two names"
|
||||
);
|
||||
{
|
||||
let name = "crank-arm";
|
||||
let mut s = open(name);
|
||||
let bodies: Vec<String> = s.design.as_ref().unwrap().bodies.iter().map(|b| b.name.clone()).collect();
|
||||
assert_eq!(bodies, [CRANK_HALF, "CrankArm/b"]);
|
||||
// One datum, the symmetry plane, hidden.
|
||||
assert!(s.model.datums().len() == 1 && s.model.datums().keys().all(|d| !s.shows(crate::ItemKind::Datum, d)), "datums shown");
|
||||
assert!(!s.is_dirty(), "a sample just opened has nothing to save");
|
||||
assert!(s.model.ties().is_empty(), "no ties");
|
||||
let elements = s.model.elements().values().filter(|e| e.kind == fieldcraft_model::ElementKind::Hex20).count();
|
||||
assert_eq!(elements, s.model.elements().len());
|
||||
let mut set = |name: &str, bodies: &[&str]| {
|
||||
s.execute("model.set.create", &json!({"name": name, "geometry": bodies.iter().map(|b| json!({"body": b})).collect::<Vec<_>>()}))
|
||||
.unwrap();
|
||||
s.model.resolve_set(name).unwrap()
|
||||
};
|
||||
let (a, b) = (set("half_a", &[CRANK_HALF]), set("half_b", &["CrankArm/b"]));
|
||||
assert_eq!(a.elements.len(), b.elements.len());
|
||||
assert_eq!(a.elements.len() + b.elements.len(), elements);
|
||||
assert_eq!(a.faces.len(), b.faces.len(), "the halves' skins are alike");
|
||||
let shared = a.nodes.iter().filter(|n| b.nodes.binary_search(n).is_ok()).count();
|
||||
assert!(shared > 100, "{shared}");
|
||||
assert_eq!(a.nodes.len() + b.nodes.len() - shared, s.model.nodes().len());
|
||||
let q = s.execute("mesh.quality", &json!({})).unwrap();
|
||||
assert_eq!(q["valid"].as_u64().unwrap() as usize, elements, "{q}");
|
||||
let metric = |m: &str, k: &str| q["metrics"][m][k].as_f64().unwrap();
|
||||
assert!(metric("scaled_jacobian", "min") >= 0.37, "{q}");
|
||||
assert!(metric("edge_ratio", "max") <= 10.0, "{q}");
|
||||
let members = |set: &str| s.model.sets().get(set).map_or(Vec::new(), |x| x.geometry.iter().map(|g| g.body.clone()).collect::<Vec<_>>());
|
||||
for set in ["spindle", "pedal"] {
|
||||
let bodies = members(set);
|
||||
assert!(bodies.iter().any(|b| b == CRANK_HALF) && bodies.iter().any(|b| b == "CrankArm/b"), "{set}: {bodies:?}");
|
||||
assert!(!s.model.resolve_set(set).unwrap().faces.is_empty(), "{set}");
|
||||
}
|
||||
let faces = |set: &str| s.model.sets().get(set).map_or(0, |x| x.geometry.len());
|
||||
assert_eq!((faces("spindle"), faces("pedal")), (10, 4), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Solved, the crank's root bends as a beam: σxx on the arm's sides at x = 29 mm (35.6 mm
|
||||
/// wide, 16 thick, 141 mm from the pedal) within 3 % of M/Z = 1500 · 141 / (16 · 35.6² / 6) =
|
||||
/// 62.6 MPa, equal and opposite on the two mirror-image sides, and the spindle carries the
|
||||
/// whole load.
|
||||
#[test]
|
||||
#[ignore = "heavy: cargo xtask test --heavy (CI heavy job)"]
|
||||
fn the_crank_arm_root_bends_as_the_beam_formula_says() {
|
||||
let mut s = open("crank-arm");
|
||||
let elements = s.model.elements().values().filter(|e| e.kind == fieldcraft_model::ElementKind::Hex20).count();
|
||||
assert_eq!(elements, s.model.elements().len());
|
||||
let faces = |set: &str| s.model.sets().get(set).map_or(0, |x| x.geometry.len());
|
||||
assert_eq!((faces("spindle"), faces("pedal")), (8, 2));
|
||||
s.execute("solve.run", &json!({})).unwrap();
|
||||
let half_width: f64 = 19.0 - 7.0 * 29.0 / 170.0;
|
||||
let probe = s.execute("solve.probe", &json!({"step": "Pedal", "at": [[29.0, -half_width, 8.0], [29.0, half_width, 8.0]]})).unwrap();
|
||||
@@ -757,10 +874,27 @@ mod tests {
|
||||
for (i, sign) in [(0, -1.0), (1, 1.0)] {
|
||||
assert!((sign * sxx(i) - hand).abs() < 0.03 * hand, "{} against {hand} MPa: {probe}", sxx(i));
|
||||
}
|
||||
assert!((sxx(0) + sxx(1)).abs() < 0.01 * hand, "{probe}");
|
||||
let reaction = s.execute("results.reactions", &json!({"step": "Pedal", "sets": ["spindle"]})).unwrap();
|
||||
assert!((reaction["sets"][0]["force"][1].as_f64().unwrap() - PEDAL_LOAD).abs() < 1e-6, "{reaction}");
|
||||
}
|
||||
|
||||
/// The conformity of `s`'s mesh ([`fieldcraft_mesh::quality::conformity`]).
|
||||
fn conformity(s: &Session) -> fieldcraft_mesh::quality::Conformity {
|
||||
let nodes: Vec<(u32, [f64; 3])> = s.model.nodes().iter().map(|(l, n)| (*l, n.xyz)).collect();
|
||||
let elements = s.model.elements().iter().map(|(l, e)| (*l, e.kind, e.nodes.as_slice()));
|
||||
fieldcraft_mesh::quality::conformity(&nodes, elements, 1e-6).unwrap()
|
||||
}
|
||||
|
||||
/// The crank arm's hex20 mesh has no crack (#260): its free faces close up across the cells
|
||||
/// and the mirror plane, no two nodes coincide and every element edge has one mid-side node.
|
||||
#[test]
|
||||
fn the_crank_arm_hex20_mesh_is_conforming() {
|
||||
let s = open("crank-arm");
|
||||
let c = conformity(&s);
|
||||
assert!(c.is_conforming(), "{:?} {:?} {:?}", c.open_edges.first(), c.coincident.first(), c.midside_mismatches.first());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_drop_test_opens_ready_to_solve() {
|
||||
let s = open("drop-test");
|
||||
|
||||
@@ -33,6 +33,12 @@ pub struct Field {
|
||||
pub default: Option<&'static str>,
|
||||
/// What an empty field means ("every body", "1/25 of the diagonal"), or a short note.
|
||||
pub hint: &'static str,
|
||||
/// What the field means, in a sentence or two, with a typical value: the form's tooltip and
|
||||
/// the JSON Schema description. The unit is added from the field's dimension ([`Field::help_text`]).
|
||||
pub help: &'static str,
|
||||
/// For a [`Kind::Choice`]: a one-line note per option value (what it needs), shown under the
|
||||
/// field for the option chosen.
|
||||
pub notes: &'static [(&'static str, &'static str)],
|
||||
}
|
||||
|
||||
/// What a field holds.
|
||||
@@ -118,6 +124,15 @@ pub enum Collection {
|
||||
SolvedStep,
|
||||
/// A body of the open design.
|
||||
Body,
|
||||
/// A datum plane, axis or point.
|
||||
Datum,
|
||||
/// A datum plane.
|
||||
DatumPlane,
|
||||
/// A datum axis.
|
||||
DatumAxis,
|
||||
/// A datum point.
|
||||
DatumPoint,
|
||||
Partition,
|
||||
}
|
||||
|
||||
impl Collection {
|
||||
@@ -138,6 +153,11 @@ impl Collection {
|
||||
Collection::Step => "step",
|
||||
Collection::SolvedStep => "solved step",
|
||||
Collection::Body => "body",
|
||||
Collection::Datum => "datum",
|
||||
Collection::DatumPlane => "datum plane",
|
||||
Collection::DatumAxis => "datum axis",
|
||||
Collection::DatumPoint => "datum point",
|
||||
Collection::Partition => "partition",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -162,6 +182,11 @@ impl Session {
|
||||
Collection::Step => Box::new(m.steps().iter().map(|s| s.name.as_str())),
|
||||
Collection::SolvedStep => Box::new(self.solved_steps()),
|
||||
Collection::Body => Box::new(self.design.iter().flat_map(|d| d.bodies.iter().map(|b| b.name.as_str()))),
|
||||
Collection::Datum => Box::new(m.datums().keys().map(String::as_str)),
|
||||
Collection::DatumPlane => Box::new(m.datums().iter().filter(|(_, d)| d.plane().is_some()).map(|(n, _)| n.as_str())),
|
||||
Collection::DatumAxis => Box::new(m.datums().iter().filter(|(_, d)| d.axis().is_some()).map(|(n, _)| n.as_str())),
|
||||
Collection::DatumPoint => Box::new(m.datums().iter().filter(|(_, d)| d.point().is_some()).map(|(n, _)| n.as_str())),
|
||||
Collection::Partition => Box::new(m.partitions().iter().map(|p| p.name.as_str())),
|
||||
};
|
||||
names.take(MAX_NAMES).map(str::to_string).collect()
|
||||
}
|
||||
@@ -202,6 +227,43 @@ pub enum Dim {
|
||||
}
|
||||
|
||||
impl Dim {
|
||||
/// The dimension's name ("stress", "length"); `None` for [`Dim::None`].
|
||||
pub fn name(self) -> Option<&'static str> {
|
||||
Some(match self {
|
||||
Dim::None => return None,
|
||||
Dim::Length | Dim::Millimetre => "length",
|
||||
Dim::Area => "area",
|
||||
Dim::Stress => "stress",
|
||||
Dim::Density => "density",
|
||||
Dim::Force => "force",
|
||||
Dim::Moment => "moment",
|
||||
Dim::Mass => "mass",
|
||||
Dim::Inertia => "rotary inertia",
|
||||
Dim::Time => "time",
|
||||
Dim::Velocity => "velocity",
|
||||
Dim::Acceleration => "acceleration",
|
||||
Dim::AngularVelocity => "angular velocity",
|
||||
Dim::Stiffness => "stiffness",
|
||||
Dim::Damping => "damping",
|
||||
Dim::Viscosity => "viscosity",
|
||||
Dim::ForcePerVolume => "force per volume",
|
||||
Dim::Power => "power",
|
||||
Dim::HeatFlux => "heat flux",
|
||||
Dim::FilmCoefficient => "film coefficient",
|
||||
Dim::Conductivity => "conductivity",
|
||||
Dim::SpecificHeat => "specific heat",
|
||||
Dim::Expansion => "expansion",
|
||||
Dim::Temperature => "temperature",
|
||||
Dim::Degree => "angle",
|
||||
Dim::Hertz => "frequency",
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether its unit follows the model's unit system (a fixed unit such as degrees does not).
|
||||
pub fn follows_system(self) -> bool {
|
||||
self.name().is_some() && self.unit(UnitSystem::Unspecified).is_none()
|
||||
}
|
||||
|
||||
/// Its unit in `system`, or `None` (no unit, or the system is unspecified).
|
||||
pub fn unit(self, system: UnitSystem) -> Option<String> {
|
||||
let fixed = match self {
|
||||
@@ -255,7 +317,7 @@ impl Dim {
|
||||
// ---- Building fields (const, so schemas are static tables) ----
|
||||
|
||||
const fn field(key: &'static str, label: &'static str, kind: Kind) -> Field {
|
||||
Field { key, label, kind, required: false, default: None, hint: "" }
|
||||
Field { key, label, kind, required: false, default: None, hint: "", help: "", notes: &[] }
|
||||
}
|
||||
|
||||
impl Field {
|
||||
@@ -271,8 +333,62 @@ impl Field {
|
||||
pub const fn hint(self, hint: &'static str) -> Field {
|
||||
Field { hint, ..self }
|
||||
}
|
||||
/// What it means ([`Field::help`]).
|
||||
pub const fn help(self, help: &'static str) -> Field {
|
||||
Field { help, ..self }
|
||||
}
|
||||
|
||||
/// A one-line note per option value ([`Field::notes`]).
|
||||
pub const fn notes(self, notes: &'static [(&'static str, &'static str)]) -> Field {
|
||||
Field { notes, ..self }
|
||||
}
|
||||
/// The note for this option value (the default when `None`).
|
||||
pub fn note(&self, value: Option<&str>) -> Option<&'static str> {
|
||||
let value = value.or_else(|| self.default.map(|d| d.trim_matches('"')))?;
|
||||
self.notes.iter().find(|(v, _)| *v == value).map(|(_, n)| *n)
|
||||
}
|
||||
|
||||
/// Its physical dimension, for a number or a vector of numbers.
|
||||
pub fn dim(&self) -> Option<Dim> {
|
||||
match self.kind {
|
||||
Kind::Number { dim, .. } | Kind::Vector { dim, .. } => Some(dim),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// What its value is measured in, as a form shows it: the unit in `system` ("MPa"), or, with
|
||||
/// no unit system, the dimension in brackets ("[stress]"). `None` for a number without a unit.
|
||||
pub fn unit_label(&self, system: UnitSystem) -> Option<String> {
|
||||
let dim = self.dim()?;
|
||||
dim.unit(system).or_else(|| dim.name().map(|n| format!("[{n}]")))
|
||||
}
|
||||
|
||||
/// The help as the form's tooltip shows it: [`Field::help`] and the unit (or, with no unit system, the dimension and where to set the system).
|
||||
pub fn help_text(&self, system: UnitSystem) -> String {
|
||||
let mut out = self.help.to_string();
|
||||
let mut line = |s: String| {
|
||||
if !out.is_empty() {
|
||||
out.push('\n');
|
||||
}
|
||||
out.push_str(&s);
|
||||
};
|
||||
if let Some(dim) = self.dim() {
|
||||
match (dim.unit(system), dim.name()) {
|
||||
(Some(u), _) => line(format!("Unit: {u}.")),
|
||||
(None, Some(n)) => {
|
||||
let hint = if system == UnitSystem::Unspecified { format!(" {UNITS_HINT}") } else { String::new() };
|
||||
line(format!("Unit: a {n} in the model's units.{hint}"))
|
||||
}
|
||||
(None, None) => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// What a form says when the model has no unit system.
|
||||
pub const UNITS_HINT: &str = "Set a unit system: Properties › Units.";
|
||||
|
||||
pub const fn num(key: &'static str, label: &'static str, dim: Dim) -> Field {
|
||||
field(key, label, Kind::Number { dim, min: None, max: None })
|
||||
}
|
||||
@@ -336,7 +452,7 @@ pub const fn variant(tag: &'static str, label: &'static str, fields: &'static [F
|
||||
}
|
||||
|
||||
/// The `name` of a new or edited definition.
|
||||
pub const NAME: Field = text("name", "Name").req();
|
||||
pub const NAME: Field = text("name", "Name").req().help("A name for it, unique among its kind; other definitions refer to it by this name.");
|
||||
|
||||
impl Kind {
|
||||
/// The variant of `tag`, for [`Kind::Variants`].
|
||||
@@ -439,26 +555,223 @@ pub fn switch_variant(f: &Field, common: &[Field], old: &Map<String, Value>, tag
|
||||
out
|
||||
}
|
||||
|
||||
/// A problem with a field's value, for the form to show beside it.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
/// A problem with a field's value: the field, where it is, and what is wrong. [`Problem::for_form`]
|
||||
/// phrases it by the field's label (the form), [`Problem::for_agents`] by its JSON path (agents,
|
||||
/// the engine's messages).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Problem {
|
||||
/// The JSON path of the field (`elastic/young`).
|
||||
/// The JSON path of the field (`elastic/young`, `rows/0/name`); empty for the parameters as a
|
||||
/// whole.
|
||||
pub path: String,
|
||||
pub message: String,
|
||||
/// The field it is about; `None` for the parameters as a whole. For a variant's tag, the
|
||||
/// [`Kind::Variants`] field.
|
||||
pub field: Option<&'static Field>,
|
||||
pub kind: ProblemKind,
|
||||
}
|
||||
|
||||
/// What is wrong with a value.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum ProblemKind {
|
||||
/// Left out (or empty text).
|
||||
Required,
|
||||
/// Not a finite number.
|
||||
NotANumber,
|
||||
/// A number below the field's minimum.
|
||||
Below(f64),
|
||||
/// A number above the field's maximum.
|
||||
Above(f64),
|
||||
/// Not a whole number in `min..=max`.
|
||||
NotAWholeNumber {
|
||||
min: i64,
|
||||
max: i64,
|
||||
},
|
||||
NotText,
|
||||
NotABool,
|
||||
/// Not one of the field's choices (or, for [`Kind::Either`], of its options).
|
||||
NotAChoice,
|
||||
/// Not a list of `len` numbers.
|
||||
NotAVector {
|
||||
len: usize,
|
||||
},
|
||||
NotNames,
|
||||
NotAnObject,
|
||||
/// A variant tag the field does not have (`None`: no tag at all).
|
||||
UnknownVariant(Option<String>),
|
||||
/// More rows than `max`, or not a list.
|
||||
TooManyRows {
|
||||
max: usize,
|
||||
},
|
||||
/// Not a number greater than 0.
|
||||
NotPositive,
|
||||
/// Not a number in `min..=max`.
|
||||
NotInRange {
|
||||
min: f64,
|
||||
max: f64,
|
||||
},
|
||||
/// Not a list of at most `max` of `what` ("[x, y, z]", "labels").
|
||||
NotAList {
|
||||
max: usize,
|
||||
what: &'static str,
|
||||
},
|
||||
NotAName,
|
||||
NotAPath,
|
||||
/// Wrong for a reason the schema does not describe: what it must be or do instead
|
||||
/// ("names the region of 2D elements; a solid block fills its body").
|
||||
Invalid(String),
|
||||
}
|
||||
|
||||
impl PartialEq for Problem {
|
||||
/// Problems are equal when they are about the same path and are the same problem (the field
|
||||
/// is where the path leads).
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.path == other.path && self.kind == other.kind
|
||||
}
|
||||
}
|
||||
|
||||
impl Problem {
|
||||
fn new(path: String, field: &'static Field, kind: ProblemKind) -> Self {
|
||||
Problem { path, field: Some(field), kind }
|
||||
}
|
||||
|
||||
/// A problem with the value at `path`, its field not looked up yet ([`Problem::in_form`]).
|
||||
pub fn at(path: impl Into<String>, kind: ProblemKind) -> Self {
|
||||
Problem { path: path.into(), field: None, kind }
|
||||
}
|
||||
|
||||
/// The problem with its field looked up in `fields` (when it has none yet and the path is
|
||||
/// there).
|
||||
pub fn in_form(mut self, fields: &'static [Field]) -> Self {
|
||||
if self.field.is_none() && !self.path.is_empty() {
|
||||
self.field = field_at(fields, &self.path);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// What the value must be, without the field's name ("required", "at least 0").
|
||||
pub fn expected(&self) -> String {
|
||||
let f = self.field;
|
||||
match &self.kind {
|
||||
ProblemKind::Required => "required".into(),
|
||||
ProblemKind::NotANumber => "a number".into(),
|
||||
ProblemKind::Below(lo) => format!("at least {lo}"),
|
||||
ProblemKind::Above(hi) => format!("at most {hi}"),
|
||||
ProblemKind::NotAWholeNumber { min, max } => format!("a whole number in {min}..={max}"),
|
||||
ProblemKind::NotText => "text".into(),
|
||||
ProblemKind::NotABool => "true or false".into(),
|
||||
ProblemKind::NotAChoice => match f.map(|f| f.kind) {
|
||||
Some(Kind::Choice(options)) => format!("one of {}", options.iter().map(|(o, _)| *o).collect::<Vec<_>>().join(", ")),
|
||||
Some(Kind::Either(options)) => format!("one of {}", options.iter().map(|o| o.key).collect::<Vec<_>>().join(", ")),
|
||||
_ => "one of the choices".into(),
|
||||
},
|
||||
ProblemKind::NotAVector { len } => format!("{len} numbers"),
|
||||
ProblemKind::NotNames => "a list of names".into(),
|
||||
ProblemKind::NotAnObject if f.is_none() => "a JSON object".into(),
|
||||
ProblemKind::NotAnObject => "an object".into(),
|
||||
ProblemKind::UnknownVariant(Some(t)) => format!("a known {} (not `{t}`)", f.map_or("type".into(), |f| f.label.to_lowercase())),
|
||||
ProblemKind::UnknownVariant(None) => match f.map(|f| f.kind) {
|
||||
Some(Kind::Variants { tag, .. }) => format!("an object with a known `{tag}`"),
|
||||
_ => "an object with a known type".into(),
|
||||
},
|
||||
ProblemKind::TooManyRows { max } => format!("a list of at most {max} rows"),
|
||||
ProblemKind::NotPositive => "a positive number".into(),
|
||||
ProblemKind::NotInRange { min, max } => format!("a number in {min}..={max}"),
|
||||
ProblemKind::NotAList { max, what } => format!("a list of at most {max} {what}"),
|
||||
ProblemKind::NotAName => "a name".into(),
|
||||
ProblemKind::NotAPath => "a file path".into(),
|
||||
ProblemKind::Invalid(why) => why.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The problem as agents read it, naming the field by its JSON path:
|
||||
/// "`elastic/young` is required", "`bands` must be a whole number in 2..=24".
|
||||
pub fn for_agents(&self) -> String {
|
||||
self.phrase(Naming::Key)
|
||||
}
|
||||
|
||||
/// The problem as a form shows it, naming the field by its label and saying what to do:
|
||||
/// "Material: choose a material", "Young's modulus: must be at least 0".
|
||||
pub fn for_form(&self) -> String {
|
||||
self.phrase(Naming::Label)
|
||||
}
|
||||
|
||||
/// The one phrasing of a problem, naming the field by its key or by its label.
|
||||
pub fn phrase(&self, naming: Naming) -> String {
|
||||
let by_label = naming == Naming::Label;
|
||||
let field = self.field.filter(|_| by_label);
|
||||
let subject = match field {
|
||||
Some(f) => format!("{}:", f.label),
|
||||
None if self.path.is_empty() => if by_label { "The parameters" } else { "the parameters" }.to_string(),
|
||||
None => format!("`{}`", self.path),
|
||||
};
|
||||
let required = self.kind == ProblemKind::Required;
|
||||
let what = match (field.map(|f| f.kind), &self.kind) {
|
||||
(_, ProblemKind::Invalid(why)) => why.clone(),
|
||||
(None, _) if required => "is required".into(),
|
||||
(None, _) => format!("must be {}", self.expected()),
|
||||
(Some(Kind::Ref(c)), _) if required => format!("choose {}", article(c.label())),
|
||||
(Some(Kind::RefList(c)), _) if required => format!("choose at least one {}", c.label()),
|
||||
(Some(Kind::Either(options)), _) => {
|
||||
format!("choose {}", options.iter().map(|o| article(&lower(o.label))).collect::<Vec<_>>().join(" or "))
|
||||
}
|
||||
(Some(Kind::Choice(options)), _) => format!("choose one of {}", options.iter().map(|(_, l)| *l).collect::<Vec<_>>().join(", ")),
|
||||
(Some(Kind::Variants { .. }), _) => format!("choose {}", article(&lower(field.map_or("", |f| f.label)))),
|
||||
(Some(Kind::Path { .. }), _) if required => "enter a path".into(),
|
||||
(Some(Kind::Text), _) if required && field.is_some_and(|f| f.key == "name") => "enter a name".into(),
|
||||
(Some(_), _) if required => "required".into(),
|
||||
(Some(_), _) => format!("must be {}", self.expected()),
|
||||
};
|
||||
format!("{subject} {what}")
|
||||
}
|
||||
}
|
||||
|
||||
/// How a problem names its field: by its JSON path (agents) or by its label (a form).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Naming {
|
||||
Key,
|
||||
Label,
|
||||
}
|
||||
|
||||
/// A command's problem with `params`, made as precise as its form `fields` can: when the
|
||||
/// command names a group (`plastic`) and the form finds a problem with a field inside it
|
||||
/// (`plastic/yield_stress` left out), that problem; otherwise the command's own, with its field
|
||||
/// looked up.
|
||||
pub fn refine(fields: &'static [Field], params: &Value, problem: Problem) -> Problem {
|
||||
let inside = |p: &Problem| p.path.strip_prefix(problem.path.as_str()).is_some_and(|r| r.starts_with('/'));
|
||||
if !problem.path.is_empty()
|
||||
&& let Some(precise) = problems(fields, params).into_iter().find(inside)
|
||||
{
|
||||
return precise;
|
||||
}
|
||||
problem.in_form(fields)
|
||||
}
|
||||
|
||||
/// "a material", "an element".
|
||||
fn article(noun: &str) -> String {
|
||||
let an = noun.starts_with(['a', 'e', 'i', 'o', 'u']);
|
||||
format!("{} {noun}", if an { "an" } else { "a" })
|
||||
}
|
||||
|
||||
/// A label lower-cased, but not its acronyms ("Reference point" → "reference point", "RBE2" stays).
|
||||
fn lower(label: &str) -> String {
|
||||
let mut chars = label.chars();
|
||||
match (chars.next(), chars.next()) {
|
||||
(Some(c), Some(d)) if d.is_lowercase() => c.to_lowercase().chain(label.chars().skip(1)).collect(),
|
||||
_ => label.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// What is missing or out of range in `params`: required fields left out, numbers outside
|
||||
/// their range, values of the wrong kind. An empty list does not promise the command accepts
|
||||
/// them (it checks more); a problem means it would not.
|
||||
pub fn problems(fields: &[Field], params: &Value) -> Vec<Problem> {
|
||||
pub fn problems(fields: &'static [Field], params: &Value) -> Vec<Problem> {
|
||||
match params.as_object() {
|
||||
Some(obj) => object_problems(fields, obj),
|
||||
None => vec![Problem { path: String::new(), message: "the parameters must be a JSON object".into() }],
|
||||
None => vec![Problem { path: String::new(), field: None, kind: ProblemKind::NotAnObject }],
|
||||
}
|
||||
}
|
||||
|
||||
/// [`problems`] of an object's fields.
|
||||
pub fn object_problems(fields: &[Field], obj: &Map<String, Value>) -> Vec<Problem> {
|
||||
pub fn object_problems(fields: &'static [Field], obj: &Map<String, Value>) -> Vec<Problem> {
|
||||
let mut out = Vec::new();
|
||||
check(fields, obj, "", &mut out, 0);
|
||||
out
|
||||
@@ -475,7 +788,42 @@ pub fn join(prefix: &str, key: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
fn check(fields: &[Field], obj: &Map<String, Value>, prefix: &str, out: &mut Vec<Problem>, depth: usize) {
|
||||
/// The field at `path` (`elastic/young`, `rows/0/name`), for a key the engine names. A variant's
|
||||
/// tag gives its [`Kind::Variants`] field; an [`Kind::Either`] option's key gives the option.
|
||||
pub fn field_at(fields: &'static [Field], path: &str) -> Option<&'static Field> {
|
||||
let mut segments = path.split('/');
|
||||
let mut field = find(fields, segments.next()?)?;
|
||||
for (depth, segment) in segments.enumerate() {
|
||||
if depth > MAX_DEPTH {
|
||||
return None;
|
||||
}
|
||||
field = match field.kind {
|
||||
Kind::Rows { .. } if segment.parse::<usize>().is_ok() => field,
|
||||
Kind::Group(inner) | Kind::Rows { fields: inner, .. } => find(inner, segment)?,
|
||||
Kind::Variants { tag, .. } if tag == segment => field,
|
||||
Kind::Variants { variants, .. } => variants.iter().find_map(|v| find(v.fields, segment))?,
|
||||
Kind::Either(options) => options.iter().find(|o| o.key == segment)?,
|
||||
_ => return None,
|
||||
};
|
||||
}
|
||||
Some(field)
|
||||
}
|
||||
|
||||
/// The field of `fields` with key `key`, looking into flattened variants.
|
||||
fn find(fields: &'static [Field], key: &str) -> Option<&'static Field> {
|
||||
fields.iter().find_map(|f| match f.kind {
|
||||
Kind::Variants { tag, variants } if f.key.is_empty() => {
|
||||
if tag == key {
|
||||
Some(f)
|
||||
} else {
|
||||
variants.iter().find_map(|v| find(v.fields, key))
|
||||
}
|
||||
}
|
||||
_ => (f.key == key).then_some(f),
|
||||
})
|
||||
}
|
||||
|
||||
fn check(fields: &'static [Field], obj: &Map<String, Value>, prefix: &str, out: &mut Vec<Problem>, depth: usize) {
|
||||
if depth > MAX_DEPTH || out.len() > MAX_ROWS {
|
||||
return;
|
||||
}
|
||||
@@ -486,20 +834,20 @@ fn check(fields: &[Field], obj: &Map<String, Value>, prefix: &str, out: &mut Vec
|
||||
match obj.get(tag).and_then(Value::as_str) {
|
||||
Some(t) => match f.kind.variant(t) {
|
||||
Some(v) => check(v.fields, obj, prefix, out, depth + 1),
|
||||
None => out.push(Problem { path: join(prefix, tag), message: format!("`{t}` is not a {}", f.label.to_lowercase()) }),
|
||||
None => out.push(Problem::new(join(prefix, tag), f, ProblemKind::UnknownVariant(Some(t.to_string())))),
|
||||
},
|
||||
None if f.required => out.push(Problem { path: join(prefix, tag), message: "required".into() }),
|
||||
None if f.required => out.push(Problem::new(join(prefix, tag), f, ProblemKind::Required)),
|
||||
None => {}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let path = join(prefix, f.key);
|
||||
match obj.get(f.key) {
|
||||
None | Some(Value::Null) if f.required => out.push(Problem { path, message: "required".into() }),
|
||||
None | Some(Value::Null) if f.required => out.push(Problem::new(path, f, ProblemKind::Required)),
|
||||
None | Some(Value::Null) => {}
|
||||
Some(v) => {
|
||||
if let Some(message) = value_problem(f, v, &path, out, depth) {
|
||||
out.push(Problem { path, message });
|
||||
if let Some(kind) = value_problem(f, v, &path, out, depth) {
|
||||
out.push(Problem::new(path, f, kind));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -507,39 +855,39 @@ fn check(fields: &[Field], obj: &Map<String, Value>, prefix: &str, out: &mut Vec
|
||||
}
|
||||
|
||||
/// What is wrong with `v` as the value of `f`; nested problems go to `out`.
|
||||
fn value_problem(f: &Field, v: &Value, path: &str, out: &mut Vec<Problem>, depth: usize) -> Option<String> {
|
||||
fn value_problem(f: &'static Field, v: &Value, path: &str, out: &mut Vec<Problem>, depth: usize) -> Option<ProblemKind> {
|
||||
match f.kind {
|
||||
Kind::Number { min, max, .. } => match (v.as_f64().filter(|x| x.is_finite()), min, max) {
|
||||
(None, ..) => Some("a number".into()),
|
||||
(Some(x), Some(lo), _) if x < lo => Some(format!("at least {lo}")),
|
||||
(Some(x), _, Some(hi)) if x > hi => Some(format!("at most {hi}")),
|
||||
(None, ..) => Some(ProblemKind::NotANumber),
|
||||
(Some(x), Some(lo), _) if x < lo => Some(ProblemKind::Below(lo)),
|
||||
(Some(x), _, Some(hi)) if x > hi => Some(ProblemKind::Above(hi)),
|
||||
_ => None,
|
||||
},
|
||||
Kind::Integer { min, max } => match v.as_i64() {
|
||||
Some(x) if (min..=max).contains(&x) => None,
|
||||
_ => Some(format!("a whole number in {min}..={max}")),
|
||||
_ => Some(ProblemKind::NotAWholeNumber { min, max }),
|
||||
},
|
||||
Kind::Text | Kind::Path { .. } | Kind::Ref(_) => match v.as_str() {
|
||||
Some(s) if f.required && s.trim().is_empty() => Some("required".into()),
|
||||
Some(s) if f.required && s.trim().is_empty() => Some(ProblemKind::Required),
|
||||
Some(_) => None,
|
||||
None => Some("text".into()),
|
||||
None => Some(ProblemKind::NotText),
|
||||
},
|
||||
Kind::Bool => (!v.is_boolean()).then(|| "true or false".into()),
|
||||
Kind::Bool => (!v.is_boolean()).then_some(ProblemKind::NotABool),
|
||||
Kind::Choice(options) => match v.as_str() {
|
||||
Some(s) if options.iter().any(|(o, _)| *o == s) => None,
|
||||
_ => Some(format!("one of {}", options.iter().map(|(o, _)| *o).collect::<Vec<_>>().join(", "))),
|
||||
_ => Some(ProblemKind::NotAChoice),
|
||||
},
|
||||
Kind::Vector { labels, nullable, .. } => match v.as_array() {
|
||||
Some(a) if a.len() == labels.len() && a.iter().all(|x| x.as_f64().is_some_and(f64::is_finite) || (nullable && x.is_null())) => None,
|
||||
_ => Some(format!("{} numbers", labels.len())),
|
||||
_ => Some(ProblemKind::NotAVector { len: labels.len() }),
|
||||
},
|
||||
Kind::RefList(_) => (!v.as_array().is_some_and(|a| a.iter().all(Value::is_string))).then(|| "a list of names".into()),
|
||||
Kind::RefList(_) => (!v.as_array().is_some_and(|a| a.iter().all(Value::is_string))).then_some(ProblemKind::NotNames),
|
||||
Kind::Group(fields) => match v.as_object() {
|
||||
Some(o) => {
|
||||
check(fields, o, path, out, depth + 1);
|
||||
None
|
||||
}
|
||||
None => Some("an object".into()),
|
||||
None => Some(ProblemKind::NotAnObject),
|
||||
},
|
||||
Kind::Variants { tag, .. } => match v.as_object() {
|
||||
Some(o) => match o.get(tag).and_then(Value::as_str).and_then(|t| f.kind.variant(t)) {
|
||||
@@ -547,9 +895,9 @@ fn value_problem(f: &Field, v: &Value, path: &str, out: &mut Vec<Problem>, depth
|
||||
check(var.fields, o, path, out, depth + 1);
|
||||
None
|
||||
}
|
||||
None => Some(format!("needs a known `{tag}`")),
|
||||
None => Some(ProblemKind::UnknownVariant(None)),
|
||||
},
|
||||
None => Some("an object".into()),
|
||||
None => Some(ProblemKind::NotAnObject),
|
||||
},
|
||||
Kind::Either(options) => {
|
||||
let ok = match v {
|
||||
@@ -559,20 +907,21 @@ fn value_problem(f: &Field, v: &Value, path: &str, out: &mut Vec<Problem>, depth
|
||||
}),
|
||||
_ => false,
|
||||
};
|
||||
(!ok).then(|| format!("one of {}", options.iter().map(|o| o.key).collect::<Vec<_>>().join(", ")))
|
||||
(!ok).then_some(ProblemKind::NotAChoice)
|
||||
}
|
||||
Kind::Unit | Kind::Json => None,
|
||||
Kind::Rows { fields, max } => match v.as_array() {
|
||||
Some(a) if a.len() <= max => {
|
||||
for (i, row) in a.iter().enumerate() {
|
||||
let row_path = format!("{path}/{i}");
|
||||
match row.as_object() {
|
||||
Some(o) => check(fields, o, &format!("{path}/{i}"), out, depth + 1),
|
||||
None => out.push(Problem { path: format!("{path}/{i}"), message: "an object".into() }),
|
||||
Some(o) => check(fields, o, &row_path, out, depth + 1),
|
||||
None => out.push(Problem::new(row_path, f, ProblemKind::NotAnObject)),
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
_ => Some(format!("a list of at most {max} rows")),
|
||||
_ => Some(ProblemKind::TooManyRows { max }),
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -665,8 +1014,14 @@ fn field_schema(f: &Field, depth: usize) -> Value {
|
||||
_ => json!({}),
|
||||
};
|
||||
s["title"] = json!(f.label);
|
||||
if !f.hint.is_empty() {
|
||||
s["description"] = json!(f.hint);
|
||||
let description = match (f.help, f.hint) {
|
||||
("", "") => None,
|
||||
(help, "") => Some(help.to_string()),
|
||||
("", hint) => Some(hint.to_string()),
|
||||
(help, hint) => Some(format!("{help} Empty or default: {hint}.")),
|
||||
};
|
||||
if let Some(d) = description {
|
||||
s["description"] = json!(d);
|
||||
}
|
||||
if let Some(d) = parse_default(f) {
|
||||
s["default"] = d;
|
||||
@@ -726,6 +1081,24 @@ mod tests {
|
||||
assert!(super::problems(LOADISH, &json!([1])).len() == 1);
|
||||
}
|
||||
|
||||
/// One problem, two phrasings: by label for the form, by path for agents.
|
||||
#[test]
|
||||
fn problems_carry_their_field_and_kind() {
|
||||
let p = problems(LOADISH, &json!({"type": "pressure", "magnitude": "x"}));
|
||||
let kinds: Vec<(&str, &ProblemKind)> = p.iter().map(|p| (p.path.as_str(), &p.kind)).collect();
|
||||
assert_eq!(kinds, [("name", &ProblemKind::Required), ("magnitude", &ProblemKind::NotANumber), ("set", &ProblemKind::Required)]);
|
||||
assert_eq!(p.iter().map(Problem::for_form).collect::<Vec<_>>(), ["Name: enter a name", "Magnitude: must be a number", "Set: choose a set"]);
|
||||
assert_eq!(
|
||||
p.iter().map(Problem::for_agents).collect::<Vec<_>>(),
|
||||
["`name` is required", "`magnitude` must be a number", "`set` is required"]
|
||||
);
|
||||
let unknown = problems(LOADISH, &json!({"name": "a", "type": "spin"}));
|
||||
assert_eq!(unknown.first().map(Problem::for_form).as_deref(), Some("Type: choose a type"));
|
||||
assert_eq!(unknown.first().map(Problem::for_agents).as_deref(), Some("`type` must be a known type (not `spin`)"));
|
||||
assert_eq!(problems(LOADISH, &json!([1])).first().map(Problem::for_agents).as_deref(), Some("the parameters must be a JSON object"));
|
||||
assert!(field_at(LOADISH, "magnitude").is_some_and(|f| f.label == "Magnitude"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_schema_has_variants_and_requirements() {
|
||||
let s = json_schema(LOADISH);
|
||||
|
||||
@@ -0,0 +1,593 @@
|
||||
//! Anonymous usage analytics, off until the user agrees (docs/privacy.md).
|
||||
//!
|
||||
//! The app records [`Event`]s here; a host (the desktop app's sender thread, the web page's
|
||||
//! `fetch`) takes them in batches ([`take_batch`]) and posts [`Batch::body`] to PostHog's batch
|
||||
//! API. Nothing here touches the network.
|
||||
//!
|
||||
//! What an event can hold is fixed by its type: command ids, sample names and requirements come
|
||||
//! from the registries (`&'static str`), never from parameters, paths, file names or messages.
|
||||
//! Recording does nothing until [`enable`] (the user agreed, and the host may send); [`disable`]
|
||||
//! drops what is queued. The queue is bounded ([`MAX_QUEUED`]): when full, new events are dropped.
|
||||
//!
|
||||
//! [`Session::execute`](crate::Session::execute) counts every top-level command of a session
|
||||
//! whose [`Session::origin`](crate::Session::origin) is set (the app's own model): its id, kind,
|
||||
//! duration, whether it failed and how, and where it came from ([`Origin`]); the funnel's
|
||||
//! [`Milestone`]s and [`Event::SampleOpened`] follow from the same commands.
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::requirement::Requirement;
|
||||
use crate::{CommandKind, EngineError};
|
||||
|
||||
/// PostHog Cloud's EU ingestion host.
|
||||
pub const DEFAULT_HOST: &str = "https://eu.i.posthog.com";
|
||||
/// Events kept waiting to be sent; more are dropped.
|
||||
pub const MAX_QUEUED: usize = 1000;
|
||||
/// Events in one request.
|
||||
pub const MAX_BATCH: usize = 100;
|
||||
|
||||
/// Where a command came from.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Origin {
|
||||
/// A click: the ribbon, a menu, a form, the browser.
|
||||
Ui,
|
||||
/// The command search or the command line.
|
||||
Palette,
|
||||
/// A script or the control channel.
|
||||
Script,
|
||||
/// An AI agent through the MCP server.
|
||||
Mcp,
|
||||
}
|
||||
|
||||
impl Origin {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Origin::Ui => "ui",
|
||||
Origin::Palette => "palette",
|
||||
Origin::Script => "script",
|
||||
Origin::Mcp => "mcp",
|
||||
}
|
||||
}
|
||||
|
||||
/// Scripts and agents, which the user can leave out on their own.
|
||||
pub fn automated(self) -> bool {
|
||||
matches!(self, Origin::Script | Origin::Mcp)
|
||||
}
|
||||
}
|
||||
|
||||
/// A step of the way from a design to results, counted once per run.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Milestone {
|
||||
DesignOpened,
|
||||
Meshed,
|
||||
Solved,
|
||||
ResultsViewed,
|
||||
}
|
||||
|
||||
impl Milestone {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Milestone::DesignOpened => "design_opened",
|
||||
Milestone::Meshed => "meshed",
|
||||
Milestone::Solved => "solved",
|
||||
Milestone::ResultsViewed => "results_viewed",
|
||||
}
|
||||
}
|
||||
|
||||
fn bit(self) -> u8 {
|
||||
1 << self as u8
|
||||
}
|
||||
}
|
||||
|
||||
/// Something that happened, with only what docs/privacy.md lists.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Event {
|
||||
AppStarted,
|
||||
/// The window closed after `seconds`.
|
||||
AppClosed {
|
||||
seconds: u64,
|
||||
},
|
||||
CommandRun {
|
||||
command: &'static str,
|
||||
kind: CommandKind,
|
||||
duration_ms: u64,
|
||||
error: Option<&'static str>,
|
||||
from: Origin,
|
||||
},
|
||||
Milestone(Milestone),
|
||||
SampleOpened {
|
||||
name: &'static str,
|
||||
},
|
||||
/// A command's form closed without running it.
|
||||
FormCancelled {
|
||||
command: &'static str,
|
||||
},
|
||||
/// A command clicked before the model had what it needs.
|
||||
UnavailableClicked {
|
||||
command: &'static str,
|
||||
missing: Vec<Requirement>,
|
||||
},
|
||||
}
|
||||
|
||||
impl Event {
|
||||
pub fn name(&self) -> &'static str {
|
||||
match self {
|
||||
Event::AppStarted => "app_started",
|
||||
Event::AppClosed { .. } => "app_closed",
|
||||
Event::CommandRun { .. } => "command_run",
|
||||
Event::Milestone(_) => "milestone",
|
||||
Event::SampleOpened { .. } => "sample_opened",
|
||||
Event::FormCancelled { .. } => "form_cancelled",
|
||||
Event::UnavailableClicked { .. } => "unavailable_clicked",
|
||||
}
|
||||
}
|
||||
|
||||
/// The event's own properties.
|
||||
pub fn properties(&self) -> Map<String, Value> {
|
||||
let v = match self {
|
||||
Event::AppStarted => json!({}),
|
||||
Event::AppClosed { seconds } => json!({"duration_s": seconds}),
|
||||
Event::CommandRun { command, kind, duration_ms, error, from } => {
|
||||
let kind = match kind {
|
||||
CommandKind::Model => "model",
|
||||
CommandKind::Session => "session",
|
||||
};
|
||||
let mut v = json!({"command": command, "kind": kind, "duration_ms": duration_ms, "ok": error.is_none(), "from": from.as_str()});
|
||||
if let Some(e) = error {
|
||||
v["error"] = json!(e);
|
||||
}
|
||||
v
|
||||
}
|
||||
Event::Milestone(m) => json!({"name": m.as_str()}),
|
||||
Event::SampleOpened { name } => json!({"name": name}),
|
||||
Event::FormCancelled { command } => json!({"command": command}),
|
||||
Event::UnavailableClicked { command, missing } => json!({"command": command, "missing": missing}),
|
||||
};
|
||||
match v {
|
||||
Value::Object(m) => m,
|
||||
_ => Map::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The class of an error, without its message (which can name the user's files and values).
|
||||
pub fn error_class(e: &EngineError) -> &'static str {
|
||||
match e {
|
||||
EngineError::UnknownCommand(_) => "unknown_command",
|
||||
EngineError::Params(_) | EngineError::Param(_) => "params",
|
||||
EngineError::Model(_) => "model",
|
||||
EngineError::Geometry(_) => "geometry",
|
||||
EngineError::Mesh(_) => "mesh",
|
||||
EngineError::File(_) => "file",
|
||||
EngineError::Deck(_) => "deck",
|
||||
EngineError::Solver(_) => "solver",
|
||||
EngineError::Explicit(_) => "explicit",
|
||||
EngineError::Fluid(_) => "fluid",
|
||||
EngineError::Unavailable(_) => "unavailable",
|
||||
EngineError::Internal { .. } => "internal",
|
||||
}
|
||||
}
|
||||
|
||||
/// Who is sending: the anonymous install and the build. The same for every event of a run.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Identity {
|
||||
/// A random id made for this install (not derived from the machine or the user).
|
||||
pub install_id: String,
|
||||
/// `desktop` or `web`.
|
||||
pub platform: &'static str,
|
||||
/// The operating system (`macos`, `linux`, `windows`; `web` in a browser).
|
||||
pub os: &'static str,
|
||||
pub arch: &'static str,
|
||||
pub app_version: &'static str,
|
||||
}
|
||||
|
||||
/// What [`take_batch`] hands the sender.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Batch {
|
||||
pub identity: Identity,
|
||||
pub events: Vec<Event>,
|
||||
}
|
||||
|
||||
impl Batch {
|
||||
/// The body of a POST to PostHog's `/batch/` endpoint with the project's API key: each event
|
||||
/// with the anonymous install id, the build, no person profile and no IP-based location.
|
||||
pub fn body(&self, api_key: &str) -> String {
|
||||
let id = &self.identity;
|
||||
let batch: Vec<Value> = self
|
||||
.events
|
||||
.iter()
|
||||
.map(|e| {
|
||||
let mut p = e.properties();
|
||||
p.insert("app_version".into(), json!(id.app_version));
|
||||
p.insert("platform".into(), json!(id.platform));
|
||||
p.insert("os".into(), json!(id.os));
|
||||
p.insert("arch".into(), json!(id.arch));
|
||||
p.insert("$process_person_profile".into(), json!(false));
|
||||
p.insert("$geoip_disable".into(), json!(true));
|
||||
json!({"event": e.name(), "distinct_id": id.install_id, "properties": p})
|
||||
})
|
||||
.collect();
|
||||
json!({"api_key": api_key, "batch": batch}).to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this run may record at all, before asking the user: the build has a project key,
|
||||
/// `FIELDCRAFT_TELEMETRY` (`telemetry`) is not `0`, and a run driven by automation (`--control`)
|
||||
/// or CI records only when `FIELDCRAFT_TELEMETRY=1` says so.
|
||||
pub fn allowed(has_key: bool, telemetry: Option<&str>, automation: bool, ci: bool) -> bool {
|
||||
let set = telemetry.map(|v| v.trim().to_ascii_lowercase());
|
||||
match set.as_deref() {
|
||||
Some("0" | "false" | "off" | "no") => false,
|
||||
Some("1" | "true" | "on" | "yes") => has_key,
|
||||
_ => has_key && !automation && !ci,
|
||||
}
|
||||
}
|
||||
|
||||
struct State {
|
||||
identity: Identity,
|
||||
/// Count scripts and MCP runs too.
|
||||
automation: bool,
|
||||
queue: VecDeque<Event>,
|
||||
/// Milestones already sent this run.
|
||||
reached: u8,
|
||||
/// When recording started ([`now_ms`]), for the session's length.
|
||||
started: Option<f64>,
|
||||
}
|
||||
|
||||
static STATE: Mutex<Option<State>> = Mutex::new(None);
|
||||
|
||||
fn with_state<R>(f: impl FnOnce(&mut Option<State>) -> R) -> R {
|
||||
// A poisoned lock still holds a usable queue.
|
||||
let mut g = STATE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
f(&mut g)
|
||||
}
|
||||
|
||||
/// Start recording, as `identity`, with [`Event::AppStarted`]; `automation` counts scripts and
|
||||
/// MCP runs too. Already recording, only the settings change.
|
||||
pub fn enable(identity: Identity, automation: bool) {
|
||||
let now = now_ms();
|
||||
with_state(|s| match s {
|
||||
Some(s) => {
|
||||
s.identity = identity;
|
||||
s.automation = automation;
|
||||
}
|
||||
None => *s = Some(State { identity, automation, queue: VecDeque::from([Event::AppStarted]), reached: 0, started: now }),
|
||||
});
|
||||
}
|
||||
|
||||
/// The app is closing: [`Event::AppClosed`] with how long it recorded.
|
||||
pub fn closing() {
|
||||
let now = now_ms();
|
||||
let started = with_state(|s| s.as_ref().map(|s| s.started));
|
||||
if let Some(started) = started {
|
||||
let seconds = match (started, now) {
|
||||
(Some(a), Some(b)) if b >= a => ((b - a) / 1000.0).round() as u64,
|
||||
_ => 0,
|
||||
};
|
||||
record(Event::AppClosed { seconds });
|
||||
}
|
||||
}
|
||||
|
||||
/// Stop recording and drop everything queued.
|
||||
pub fn disable() {
|
||||
with_state(|s| *s = None);
|
||||
}
|
||||
|
||||
pub fn enabled() -> bool {
|
||||
with_state(|s| s.is_some())
|
||||
}
|
||||
|
||||
/// Queue an event, when recording (and when it is no script or MCP run the user left out).
|
||||
pub fn record(event: Event) {
|
||||
with_state(|s| {
|
||||
let Some(s) = s else { return };
|
||||
match &event {
|
||||
Event::CommandRun { from, .. } if from.automated() && !s.automation => return,
|
||||
Event::Milestone(m) if s.reached & m.bit() != 0 => return,
|
||||
Event::Milestone(m) => s.reached |= m.bit(),
|
||||
_ => {}
|
||||
}
|
||||
if s.queue.len() < MAX_QUEUED {
|
||||
s.queue.push_back(event);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Up to [`MAX_BATCH`] queued events to send, oldest first; `None` when there are none.
|
||||
pub fn take_batch() -> Option<Batch> {
|
||||
with_state(|s| {
|
||||
let s = s.as_mut()?;
|
||||
if s.queue.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let n = s.queue.len().min(MAX_BATCH);
|
||||
Some(Batch { identity: s.identity.clone(), events: s.queue.drain(..n).collect() })
|
||||
})
|
||||
}
|
||||
|
||||
/// Events waiting to be sent.
|
||||
pub fn queued() -> usize {
|
||||
with_state(|s| s.as_ref().map_or(0, |s| s.queue.len()))
|
||||
}
|
||||
|
||||
/// A clock in milliseconds for command durations. The plain wasm target has none: the web page
|
||||
/// sets one ([`set_clock`]).
|
||||
static CLOCK: Mutex<Option<fn() -> f64>> = Mutex::new(None);
|
||||
|
||||
/// Use `clock` (milliseconds, any origin) for command durations.
|
||||
pub fn set_clock(clock: fn() -> f64) {
|
||||
*CLOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(clock);
|
||||
}
|
||||
|
||||
fn now_ms() -> Option<f64> {
|
||||
if let Some(c) = *CLOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner) {
|
||||
return Some(c());
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
|
||||
Some(START.get_or_init(std::time::Instant::now).elapsed().as_secs_f64() * 1000.0)
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
None
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// Commands running on this thread: only the outermost is counted.
|
||||
static DEPTH: Cell<u32> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
/// A command being counted, from [`Session::execute`](crate::Session::execute): `None` when it
|
||||
/// is not (not recording, no origin, or a command inside another).
|
||||
pub(crate) struct Timer {
|
||||
started: Option<f64>,
|
||||
from: Option<Origin>,
|
||||
}
|
||||
|
||||
impl Timer {
|
||||
pub(crate) fn start(from: Option<Origin>) -> Timer {
|
||||
let outer = DEPTH.with(|d| {
|
||||
d.set(d.get() + 1);
|
||||
d.get() == 1
|
||||
});
|
||||
let from = from.filter(|_| outer && enabled());
|
||||
Timer { started: from.and_then(|_| now_ms()), from }
|
||||
}
|
||||
|
||||
/// Whether this command is counted.
|
||||
pub(crate) fn counting(&self) -> bool {
|
||||
self.from.is_some()
|
||||
}
|
||||
|
||||
/// The command ended: count it, and the milestone it reached.
|
||||
pub(crate) fn done(
|
||||
&self,
|
||||
command: &'static str,
|
||||
kind: CommandKind,
|
||||
error: Option<&EngineError>,
|
||||
milestone: Option<Milestone>,
|
||||
sample: Option<&'static str>,
|
||||
) {
|
||||
let Some(from) = self.from else { return };
|
||||
let duration_ms = match (self.started, now_ms()) {
|
||||
(Some(a), Some(b)) if b >= a => (b - a).round() as u64,
|
||||
_ => 0,
|
||||
};
|
||||
record(Event::CommandRun { command, kind, duration_ms, error: error.map(error_class), from });
|
||||
if error.is_none() {
|
||||
if let Some(m) = milestone {
|
||||
record(Event::Milestone(m));
|
||||
}
|
||||
if let Some(name) = sample {
|
||||
record(Event::SampleOpened { name });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Timer {
|
||||
fn drop(&mut self) {
|
||||
DEPTH.with(|d| d.set(d.get().saturating_sub(1)));
|
||||
}
|
||||
}
|
||||
|
||||
/// The milestone a successful `command` reaches; `elements` is the element count before and
|
||||
/// after it.
|
||||
pub(crate) fn milestone(command: &str, elements: (usize, usize)) -> Option<Milestone> {
|
||||
match command {
|
||||
"geometry.open" | "geometry.import.mesh" | "file.open" => Some(Milestone::DesignOpened),
|
||||
c if c.starts_with("mesh.") && elements.1 > elements.0 => Some(Milestone::Meshed),
|
||||
// Solvers, not the queries on a solved step.
|
||||
c if c.starts_with("solve.") && !matches!(c, "solve.probe" | "solve.history") => Some(Milestone::Solved),
|
||||
c if c.starts_with("results.") && !matches!(c, "results.reactions" | "results.clear") => Some(Milestone::ResultsViewed),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Serialises the tests (and other code) that turn the process-wide recording on.
|
||||
#[doc(hidden)]
|
||||
pub static TEST_LOCK: Mutex<()> = Mutex::new(());
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::Session;
|
||||
|
||||
fn identity() -> Identity {
|
||||
Identity { install_id: "00000000-0000-4000-8000-000000000000".into(), platform: "desktop", os: "test", arch: "test", app_version: "0.0.0" }
|
||||
}
|
||||
|
||||
fn take_all() -> Vec<Event> {
|
||||
std::iter::from_fn(take_batch).flat_map(|b| b.events).collect()
|
||||
}
|
||||
|
||||
/// Every string in a payload is a key, a registry name or the identity, and every number a
|
||||
/// duration: no path, file name, parameter value or message can be in it.
|
||||
pub(crate) fn assert_clean(body: &str) {
|
||||
let v: Value = serde_json::from_str(body).unwrap();
|
||||
let mut allowed: Vec<String> = crate::commands().iter().map(|c| c.id.to_string()).collect();
|
||||
allowed.extend(crate::sample::SAMPLES.iter().map(|s| s.name.to_string()));
|
||||
for e in [
|
||||
"app_started",
|
||||
"app_closed",
|
||||
"command_run",
|
||||
"milestone",
|
||||
"sample_opened",
|
||||
"form_cancelled",
|
||||
"unavailable_clicked",
|
||||
"model",
|
||||
"session",
|
||||
"ui",
|
||||
"palette",
|
||||
"script",
|
||||
"mcp",
|
||||
"design_opened",
|
||||
"meshed",
|
||||
"solved",
|
||||
"results_viewed",
|
||||
"unknown_command",
|
||||
"params",
|
||||
"geometry",
|
||||
"mesh",
|
||||
"file",
|
||||
"deck",
|
||||
"solver",
|
||||
"explicit",
|
||||
"fluid",
|
||||
"unavailable",
|
||||
"internal",
|
||||
"KEY",
|
||||
] {
|
||||
allowed.push(e.into());
|
||||
}
|
||||
let id = identity();
|
||||
allowed.extend([id.install_id, id.platform.into(), id.os.into(), id.arch.into(), id.app_version.into()]);
|
||||
fn walk(key: &str, v: &Value, allowed: &[String]) {
|
||||
match v {
|
||||
Value::String(s) => {
|
||||
// A requirement's snake_case name.
|
||||
let requirement = key == "missing" && s.chars().all(|c| c.is_ascii_lowercase() || c == '_');
|
||||
assert!(allowed.contains(s) || requirement, "`{key}`: `{s}` is not a name FieldCraft defines");
|
||||
}
|
||||
Value::Number(_) => assert!(["duration_ms", "duration_s"].contains(&key), "`{key}`: a number that is not a duration"),
|
||||
Value::Array(a) => a.iter().for_each(|x| walk(key, x, allowed)),
|
||||
Value::Object(m) => m.iter().for_each(|(k, x)| walk(k, x, allowed)),
|
||||
Value::Bool(_) | Value::Null => {}
|
||||
}
|
||||
}
|
||||
walk("", &v, &allowed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_is_queued_without_consent() {
|
||||
let _g = TEST_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
disable();
|
||||
let mut s = Session { origin: Some(Origin::Ui), ..Default::default() };
|
||||
s.run_script(&crate::sample::cantilever()).unwrap();
|
||||
record(Event::AppStarted);
|
||||
assert_eq!(queued(), 0);
|
||||
assert!(take_batch().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scripted_session_sends_only_names_and_durations() {
|
||||
let _g = TEST_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
disable();
|
||||
enable(identity(), true);
|
||||
let dir = std::env::temp_dir().join(format!("fieldcraft-usage-secret-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let design = dir.join("my-secret-bracket.solidcraft");
|
||||
std::fs::write(&design, fieldcraft_geometry::sample::plate_design(&fieldcraft_geometry::sample::Plate::default()).unwrap()).unwrap();
|
||||
let mut s = Session { origin: Some(Origin::Script), ..Default::default() };
|
||||
s.execute("geometry.open", &json!({"path": design.to_string_lossy()})).unwrap();
|
||||
s.run_script(&crate::sample::cantilever()).unwrap();
|
||||
s.execute("model.material.create", &json!({"name": "Secret alloy 7", "elastic": {"young": 123456.75, "poisson": 0.3125}})).ok();
|
||||
s.execute("solve.run", &json!({})).unwrap();
|
||||
s.execute("results.contour", &json!({"field": "von_mises"})).unwrap();
|
||||
// A failure whose message names a path, and a sample.
|
||||
assert!(s.execute("file.open", &json!({"path": dir.join("missing-secret.fieldcraft").to_string_lossy()})).is_err());
|
||||
s.execute("file.sample", &json!({"name": "cantilever"})).unwrap();
|
||||
// An unknown id is user text: not counted.
|
||||
assert!(s.execute("secret.command", &json!({})).is_err());
|
||||
let events = take_all();
|
||||
let body = Batch { identity: identity(), events: events.clone() }.body("KEY");
|
||||
assert_clean(&body);
|
||||
for secret in ["secret", "Secret", "123456", "0.3125", "1000", dir.to_string_lossy().as_ref()] {
|
||||
assert!(!body.contains(secret), "{secret} in {body}");
|
||||
}
|
||||
let names: Vec<&str> = events.iter().map(Event::name).collect();
|
||||
assert!(names.contains(&"command_run") && names.contains(&"sample_opened"), "{names:?}");
|
||||
// Inner commands (the script's steps run by execute, a sample's own script) count once.
|
||||
let runs = events.iter().filter(|e| matches!(e, Event::CommandRun { command: "file.sample", .. })).count();
|
||||
assert_eq!(runs, 1);
|
||||
let reached: Vec<_> = events.iter().filter_map(|e| if let Event::Milestone(m) = e { Some(*m) } else { None }).collect();
|
||||
for m in [Milestone::DesignOpened, Milestone::Meshed, Milestone::Solved, Milestone::ResultsViewed] {
|
||||
assert_eq!(reached.iter().filter(|r| **r == m).count(), 1, "{m:?} once: {reached:?}");
|
||||
}
|
||||
assert!(
|
||||
events.iter().any(|e| matches!(e, Event::CommandRun { command: "file.open", error: Some("file"), from: Origin::Script, .. })),
|
||||
"{events:?}"
|
||||
);
|
||||
disable();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scripts_and_agents_can_be_left_out_and_the_queue_is_bounded() {
|
||||
let _g = TEST_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
disable();
|
||||
enable(identity(), false);
|
||||
let run = |from| Event::CommandRun { command: "model.info", kind: CommandKind::Model, duration_ms: 1, error: None, from };
|
||||
record(run(Origin::Mcp));
|
||||
record(run(Origin::Script));
|
||||
record(run(Origin::Palette));
|
||||
assert_eq!(take_all(), [Event::AppStarted, run(Origin::Palette)]);
|
||||
for _ in 0..MAX_QUEUED + 50 {
|
||||
record(Event::AppStarted);
|
||||
}
|
||||
assert_eq!(queued(), MAX_QUEUED);
|
||||
let first = take_batch().unwrap();
|
||||
assert_eq!(first.events.len(), MAX_BATCH);
|
||||
assert_eq!(queued(), MAX_QUEUED - MAX_BATCH);
|
||||
// Turning it off drops what waits.
|
||||
disable();
|
||||
assert_eq!(queued(), 0);
|
||||
enable(identity(), true);
|
||||
closing();
|
||||
assert!(matches!(take_all()[..], [Event::AppStarted, Event::AppClosed { .. }]));
|
||||
disable();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_body_is_a_posthog_batch() {
|
||||
let b = Batch {
|
||||
identity: identity(),
|
||||
events: vec![Event::UnavailableClicked { command: "solve.run", missing: vec![Requirement::Step, Requirement::Material] }],
|
||||
};
|
||||
let v: Value = serde_json::from_str(&b.body("phc_test")).unwrap();
|
||||
assert_eq!(v["api_key"], "phc_test");
|
||||
let e = &v["batch"][0];
|
||||
assert_eq!((e["event"].as_str(), e["distinct_id"].as_str()), (Some("unavailable_clicked"), Some(identity().install_id.as_str())));
|
||||
assert_eq!(e["properties"]["missing"], json!(["step", "material"]));
|
||||
assert_eq!(e["properties"]["$process_person_profile"], false);
|
||||
assert_eq!(e["properties"]["$geoip_disable"], true);
|
||||
assert_clean(&b.body("KEY"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn telemetry_is_off_without_a_key_in_automation_and_ci_and_when_turned_off() {
|
||||
assert!(allowed(true, None, false, false));
|
||||
assert!(!allowed(false, None, false, false));
|
||||
assert!(!allowed(false, Some("1"), false, false));
|
||||
assert!(!allowed(true, Some("0"), false, false));
|
||||
assert!(!allowed(true, Some(" off "), false, false));
|
||||
assert!(!allowed(true, None, true, false));
|
||||
assert!(!allowed(true, None, false, true));
|
||||
assert!(!allowed(true, Some(""), true, false));
|
||||
assert!(allowed(true, Some("1"), true, true));
|
||||
}
|
||||
}
|
||||
@@ -8,11 +8,11 @@
|
||||
//! deformed shape (automatic or chosen scale) with its contour bands. Animation is not drawn: a
|
||||
//! picture shows the full deformation (a mode at its positive shape). The analysis setup's
|
||||
//! symbols ([`fieldcraft_render::glyphs`]) are drawn over the model as the viewport draws them,
|
||||
//! muted over a results plot.
|
||||
//! muted over a results plot, at their default size on screen once the camera is known.
|
||||
|
||||
use fieldcraft_model::ElementKind;
|
||||
use fieldcraft_render::contour::{Bands, band_color, split_triangle};
|
||||
use fieldcraft_render::glyphs::{GlyphColors, GlyphShow, Glyphs};
|
||||
use fieldcraft_render::glyphs::{self, GlyphColors, GlyphShow, GlyphView, Glyphs};
|
||||
use fieldcraft_render::{Aabb3, Camera, DisplayMesh, Orientation, Rgb, Scene, SceneLine, SceneTri, Vec3};
|
||||
use serde_json::Value;
|
||||
|
||||
@@ -72,6 +72,9 @@ impl Palette {
|
||||
interaction: Rgb(0x9a, 0x30, 0xc0),
|
||||
thermal: Rgb(0xe8, 0x4c, 0x00),
|
||||
label: Rgb(0x26, 0x2a, 0x32),
|
||||
datum: Rgb(0x1e, 0x8c, 0x6e),
|
||||
contact: Rgb(0x6a, 0x8a, 0x00),
|
||||
highlight: Rgb(0xd6, 0x00, 0x7f),
|
||||
},
|
||||
};
|
||||
|
||||
@@ -118,14 +121,14 @@ pub struct Shown {
|
||||
pub fn display(s: &Session) -> (DisplayMesh, Vec<String>) {
|
||||
let mut d = DisplayMesh::from_model(&s.model);
|
||||
let mut failed = Vec::new();
|
||||
for body in s.design.iter().flat_map(|d| &d.bodies) {
|
||||
for body in s.design.iter().flat_map(|d| &d.bodies).filter(|b| s.shows(fieldcraft_io::ItemKind::Body, &b.name)) {
|
||||
let mesh = body.measure().and_then(|m| body.tessellate(display_tolerance(&Aabb3 { min: m.bbox_min.into(), max: m.bbox_max.into() })));
|
||||
match mesh {
|
||||
Ok(m) => d.add_surface(&m.positions, &m.triangles, &m.tri_face),
|
||||
Err(e) => failed.push(format!("{}: {e}", body.name)),
|
||||
}
|
||||
}
|
||||
for surface in &s.surfaces {
|
||||
for surface in s.surfaces.iter().filter(|x| s.shows(fieldcraft_io::ItemKind::Surface, &x.name)) {
|
||||
d.add_surface(&surface.mesh.positions, &surface.mesh.triangles, &surface.mesh.tri_face);
|
||||
}
|
||||
(d, failed)
|
||||
@@ -140,23 +143,54 @@ fn model_scene(d: &DisplayMesh, p: &Palette) -> Scene {
|
||||
s.tris.extend(d.surface_tris.iter().map(|t| SceneTri { p: t.p, normal: t.normal, color: d.body_color(t, p.geometry, &p.bodies) }));
|
||||
}
|
||||
s.lines = d.edges.iter().map(|e| SceneLine { a: e.p[0], b: e.p[1], color: p.mesh_edge, width: EDGE_WIDTH }).collect();
|
||||
let edge = if faces_drawn { p.mesh_edge } else { p.geometry_edge };
|
||||
s.lines.extend(d.surface_edges.iter().map(|[a, b]| SceneLine { a: *a, b: *b, color: edge, width: GEOMETRY_EDGE_WIDTH }));
|
||||
if faces_drawn {
|
||||
s.lines.extend(d.surface_edges.iter().map(|[a, b]| SceneLine { a: *a, b: *b, color: p.mesh_edge, width: GEOMETRY_EDGE_WIDTH }));
|
||||
} else {
|
||||
// Over the mesh the geometry's edges are drawn along it (the element edges on them), so
|
||||
// they lie on the element faces.
|
||||
let edge = p.geometry_edge;
|
||||
s.lines.extend(d.edges.iter().filter(|e| e.feature).map(|e| SceneLine { a: e.p[0], b: e.p[1], color: edge, width: GEOMETRY_EDGE_WIDTH }));
|
||||
}
|
||||
s.lines.extend(d.lines.iter().map(|l| SceneLine { a: l.a, b: l.b, color: p.element(l.kind), width: LINE_ELEMENT_WIDTH }));
|
||||
s
|
||||
}
|
||||
|
||||
/// The scene of the session: the model, or the results view's plot, and what it shows.
|
||||
pub fn scene(s: &Session, p: &Palette) -> (Scene, Aabb3, Shown) {
|
||||
/// The model part of a picture: the model or the results view's plot, the shape the symbols sit
|
||||
/// on (the deformed one of a plot), the box around it and what it shows.
|
||||
struct Picture {
|
||||
scene: Scene,
|
||||
drawn: DisplayMesh,
|
||||
bounds: Aabb3,
|
||||
shown: Shown,
|
||||
glyphs: Glyphs,
|
||||
colors: GlyphColors,
|
||||
/// The box around the datums drawn: inside the clipping radius, never framed (#295).
|
||||
datums: Aabb3,
|
||||
}
|
||||
|
||||
impl Picture {
|
||||
/// The setup's symbols at symbol unit `unit` ([`glyphs::symbol_unit`]), in a scene of their
|
||||
/// own; notes the definitions drawn with a sample. Returns the box around them.
|
||||
fn symbols(&mut self, unit: f64, into: &mut Scene) -> Aabb3 {
|
||||
let drawn = &self.drawn;
|
||||
let view = GlyphView { show: GlyphShow::ALL, colors: &self.colors, unit, highlight: None };
|
||||
let d = self.glyphs.draw(|label| drawn.node_position(label), &view, into);
|
||||
self.shown.sampled = d.notes;
|
||||
d.bounds
|
||||
}
|
||||
}
|
||||
|
||||
fn picture(s: &Session, p: &Palette) -> Picture {
|
||||
let (base, failed) = display(s);
|
||||
let glyphs = Glyphs::from_model(&s.model);
|
||||
let mut shown = Shown { failed, sampled: glyphs.notes.clone(), ..Shown::default() };
|
||||
let glyphs = s.glyphs();
|
||||
let mut shown = Shown { failed, ..Shown::default() };
|
||||
let plot = s.results_view.as_ref().and_then(|v| s.latest_result(&v.step).map(|(r, _)| (v, r)));
|
||||
let Some((view, result)) = plot else {
|
||||
let mut bounds = base.bounds;
|
||||
let mut scene = model_scene(&base, p);
|
||||
bounds.union(glyphs.draw(|label| base.node_position(label), GlyphShow::ALL, &p.glyphs, &mut scene));
|
||||
return (scene, bounds, shown);
|
||||
let bounds = base.bounds;
|
||||
let shows = |n: &str| s.shows(fieldcraft_io::ItemKind::Datum, n);
|
||||
let datums = fieldcraft_render::glyphs::datums(&s.model, &base.bounds, &shows, None, &p.glyphs, &mut scene);
|
||||
return Picture { scene, drawn: base, bounds, shown, glyphs, colors: p.glyphs, datums };
|
||||
};
|
||||
shown.step = Some(view.step.clone());
|
||||
let pick = view.pick();
|
||||
@@ -198,11 +232,21 @@ pub fn scene(s: &Session, p: &Palette) -> (Scene, Aabb3, Shown) {
|
||||
});
|
||||
}
|
||||
}
|
||||
let symbols = glyphs.draw(|label| drawn.node_position(label), GlyphShow::ALL, &p.glyphs.over_results(p.background.1), &mut scene);
|
||||
let mut bounds = base.bounds;
|
||||
bounds.union(drawn.bounds);
|
||||
bounds.union(symbols);
|
||||
(scene, bounds, shown)
|
||||
Picture { scene, drawn, bounds, shown, glyphs, colors: p.glyphs.over_results(p.background.1), datums: Aabb3::EMPTY }
|
||||
}
|
||||
|
||||
/// The scene of the session (the model, or the results view's plot) with the setup's symbols
|
||||
/// at the model's own symbol unit, the box around it, and what it shows.
|
||||
pub fn scene(s: &Session, p: &Palette) -> (Scene, Aabb3, Shown) {
|
||||
let mut pic = picture(s, p);
|
||||
let mut symbols = Scene::default();
|
||||
let b = pic.symbols(pic.glyphs.model_unit(), &mut symbols);
|
||||
let mut scene = pic.scene;
|
||||
scene.append(symbols);
|
||||
pic.bounds.union(b);
|
||||
(scene, pic.bounds, pic.shown)
|
||||
}
|
||||
|
||||
/// A camera orientation from JSON, `{"yaw": …, "pitch": …, "distance"?: …}`: degrees, and the
|
||||
@@ -222,17 +266,31 @@ pub fn orientation(p: &Value) -> Result<Orientation> {
|
||||
Orientation::checked(yaw, pitch, distance).ok_or_else(|| bad("`yaw` and `pitch` must be finite and `distance` finite and above 0"))
|
||||
}
|
||||
|
||||
/// A PNG of the session seen from `at`, `w` × `h` pixels: framing everything drawn, or from
|
||||
/// `at`'s distance when it has one.
|
||||
/// A PNG of the session seen from `at`, `w` × `h` pixels: framing everything drawn but the
|
||||
/// datums (they are drawn at the model's extent, and framing them would only add margin), or from
|
||||
/// `at`'s distance when it has one. The symbols are drawn at their default size on screen
|
||||
/// ([`glyphs::DEFAULT_SIZE`] pixels) for that camera.
|
||||
pub fn render_png(s: &Session, at: &Orientation, w: usize, h: usize, p: &Palette) -> Result<(Vec<u8>, Shown)> {
|
||||
let (mut scene, bounds, shown) = scene(s, p);
|
||||
let mut pic = picture(s, p);
|
||||
let mut cam = Camera::default();
|
||||
let aspect = w as f64 / h.max(1) as f64;
|
||||
let unit = |cam: &Camera| cam.length_per_pixel(h as f64).and_then(|l| glyphs::symbol_unit(l, glyphs::DEFAULT_SIZE)).unwrap_or(f64::NAN);
|
||||
// Framed on the model, then again with its symbols at that camera's size, which reach a
|
||||
// little beyond it.
|
||||
cam.orient(&Orientation { distance: None, ..*at });
|
||||
cam.fit(&bounds);
|
||||
cam.fit_in(&pic.bounds, aspect, fieldcraft_render::FULL_VIEW);
|
||||
let mut symbols = Scene::default();
|
||||
let mut framed = pic.bounds;
|
||||
framed.union(pic.symbols(unit(&cam), &mut symbols));
|
||||
cam.fit_in(&framed, aspect, fieldcraft_render::FULL_VIEW);
|
||||
cam.orient(at);
|
||||
scene.radius = if bounds.is_empty() { 1.0 } else { (cam.target.dist(bounds.center()) + bounds.diagonal() * 0.5).max(1e-3) };
|
||||
let png = fieldcraft_render::render_png(&scene, &cam, w, h).map_err(|e| EngineError::Params(format!("render: {e}")))?;
|
||||
Ok((png, shown))
|
||||
symbols = Scene::default();
|
||||
let mut bounds = pic.bounds;
|
||||
bounds.union(pic.symbols(unit(&cam), &mut symbols));
|
||||
bounds.union(pic.datums);
|
||||
pic.scene.radius = if bounds.is_empty() { 1.0 } else { (cam.target.dist(bounds.center()) + bounds.diagonal() * 0.5).max(1e-3) };
|
||||
let png = fieldcraft_render::render_layers_png(&pic.scene, &[&symbols], &cam, w, h).map_err(|e| EngineError::Params(format!("render: {e}")))?;
|
||||
Ok((png, pic.shown))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -251,14 +309,19 @@ mod tests {
|
||||
s.run_script(&crate::sample::cantilever()).unwrap();
|
||||
let (model, shown) = render_png(&s, &iso, 64, 48, &Palette::LIGHT).unwrap();
|
||||
assert_eq!(shown, Shown::default());
|
||||
// The clamp's cones and the push's arrows are drawn in their colours.
|
||||
// The clamp's triangles and the push's arrows are drawn in their colours, as wireframes.
|
||||
let (scene, ..) = super::scene(&s, &Palette::LIGHT);
|
||||
assert!(scene.tris.iter().any(|t| t.color == Palette::LIGHT.glyphs.constraint));
|
||||
assert!(scene.lines.iter().any(|l| l.color == Palette::LIGHT.glyphs.constraint));
|
||||
assert!(scene.lines.iter().any(|l| l.color == Palette::LIGHT.glyphs.load));
|
||||
assert!(!scene.tris.iter().any(|t| t.color == Palette::LIGHT.glyphs.constraint));
|
||||
// And in the picture: pixels of the clamp's colour.
|
||||
let (png, _) = render_png(&s, &iso, 320, 240, &Palette::LIGHT).unwrap();
|
||||
assert!(count_color(&png, Palette::LIGHT.glyphs.constraint) > 20);
|
||||
s.execute("solve.static", &json!({})).unwrap();
|
||||
let (plot, shown) = render_png(&s, &iso, 64, 48, &Palette::LIGHT).unwrap();
|
||||
assert_ne!(model, plot);
|
||||
assert!(shown.scale > 0.0 && shown.step.is_some(), "{shown:?}");
|
||||
// A static step first shows its contours on the undeformed shape.
|
||||
assert!(shown.scale == 0.0 && shown.step.is_some(), "{shown:?}");
|
||||
let (field, min, max) = shown.contour.unwrap();
|
||||
assert_eq!(field, "von_mises");
|
||||
assert!(max.1 > min.1);
|
||||
@@ -266,8 +329,30 @@ mod tests {
|
||||
// Over the plot the symbols are muted.
|
||||
let (scene, ..) = super::scene(&s, &Palette::LIGHT);
|
||||
let muted = Palette::LIGHT.glyphs.over_results(Palette::LIGHT.background.1);
|
||||
assert!(scene.tris.iter().any(|t| t.color == muted.constraint));
|
||||
assert!(!scene.tris.iter().any(|t| t.color == Palette::LIGHT.glyphs.constraint));
|
||||
assert!(scene.lines.iter().any(|l| l.color == muted.constraint));
|
||||
assert!(!scene.lines.iter().any(|l| l.color == Palette::LIGHT.glyphs.constraint));
|
||||
}
|
||||
|
||||
/// Pixels of colour `c` (within a few levels) in a PNG.
|
||||
fn count_color(png: &[u8], c: Rgb) -> usize {
|
||||
let d = png::Decoder::new(std::io::Cursor::new(png));
|
||||
let mut r = d.read_info().unwrap();
|
||||
let mut buf = vec![0; r.output_buffer_size().unwrap()];
|
||||
let info = r.next_frame(&mut buf).unwrap();
|
||||
let close = |a: u8, b: u8| a.abs_diff(b) <= 6;
|
||||
buf[..info.buffer_size()].chunks(4).filter(|p| close(p[0], c.0) && close(p[1], c.1) && close(p[2], c.2)).count()
|
||||
}
|
||||
|
||||
/// The symbols are as large on screen in a close-up as in a distant view.
|
||||
#[test]
|
||||
fn symbols_keep_their_size_in_pictures_at_any_distance() {
|
||||
let mut s = Session::default();
|
||||
s.run_script(&crate::sample::cantilever()).unwrap();
|
||||
let at = |d: f64| orientation(&json!({"yaw": -45, "pitch": 30, "distance": d})).unwrap();
|
||||
let clamp = |d: f64| count_color(&render_png(&s, &at(d), 400, 300, &Palette::LIGHT).unwrap().0, Palette::LIGHT.glyphs.constraint);
|
||||
let (near, far) = (clamp(120.0), clamp(1200.0));
|
||||
// Zoomed out ten times, the symbols are as large (a few overlap and thin out).
|
||||
assert!(far > 30 && far * 4 > near, "near {near}, far {far}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -23,6 +23,10 @@ pub struct Design {
|
||||
/// Features that failed to rebuild. The design still opens with the bodies the rest made,
|
||||
/// as it does in SolidCraft.
|
||||
pub errors: Vec<FeatureError>,
|
||||
/// The partitions applied ([`Design::partitioned`]), in order; empty for the design as opened.
|
||||
pub cuts: Vec<crate::partition::CutReport>,
|
||||
/// The bodies as opened, before any partition: what [`Design::partitioned`] starts from.
|
||||
pub(crate) source: std::sync::Arc<Vec<Shape>>,
|
||||
}
|
||||
|
||||
/// A feature of the design that failed to rebuild.
|
||||
@@ -68,7 +72,7 @@ pub(crate) fn rebuild(doc: &Document) -> Result<Design> {
|
||||
})?;
|
||||
bodies.push(Shape { name: b.name.clone(), body: b.body.clone(), faces });
|
||||
}
|
||||
Ok(Design { name: doc.name.clone(), bodies, errors })
|
||||
Ok(Design { name: doc.name.clone(), source: std::sync::Arc::new(bodies.clone()), bodies, errors, cuts: Vec::new() })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
//! Persistent names of a body's B-rep edges.
|
||||
//!
|
||||
//! An edge is named after the faces it separates: the persistent names of its faces, sorted and
|
||||
//! joined by `|` (`F2:side:l1|F2:top`), the scheme SolidCraft names edges by. Where several edges
|
||||
//! separate the same faces (the top and bottom rim of a hole's half-cylinder against two caps
|
||||
//! cannot repeat, but the two edges between a fillet and a face it splits can), they are numbered
|
||||
//! `~0`, `~1`, … in order of position along the axis they spread most along, so the names do not
|
||||
//! depend on the order the kernel lists edges in. Because the names come from the face names, an
|
||||
//! edge keeps its name through an edit of the design that keeps its faces' names, and the cut
|
||||
//! edges of a partition are named after the `partition:<name>:a|b` faces.
|
||||
//!
|
||||
//! A shape built in code has no face names; its edges are named after the face indices.
|
||||
|
||||
use crate::{Result, Shape, SurfaceMesh};
|
||||
|
||||
/// Tessellation tolerance (a fraction of the body's size) of [`Shape::edges`]: the edge polylines
|
||||
/// are for display, picking and matching edges by position.
|
||||
pub const EDGE_TOLERANCE: f64 = 1e-3;
|
||||
|
||||
/// A B-rep edge of a body.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Edge {
|
||||
/// The persistent name (see the module docs).
|
||||
pub name: String,
|
||||
/// The faces it bounds, by face index (one or two; both the same for a seam).
|
||||
pub faces: Vec<u32>,
|
||||
/// A polyline along it, start to end.
|
||||
pub points: Vec<[f64; 3]>,
|
||||
}
|
||||
|
||||
impl Edge {
|
||||
/// The length of its polyline.
|
||||
pub fn length(&self) -> f64 {
|
||||
self.points.windows(2).map(|w| distance(w[0], w[1])).sum()
|
||||
}
|
||||
|
||||
/// The point `fraction` of its length along it from its start (0: the start, 1: the end);
|
||||
/// `None` for a fraction outside 0..=1 or an edge without points.
|
||||
pub fn point_at(&self, fraction: f64) -> Option<[f64; 3]> {
|
||||
if !(0.0..=1.0).contains(&fraction) {
|
||||
return None;
|
||||
}
|
||||
let mut left = fraction * self.length();
|
||||
for w in self.points.windows(2) {
|
||||
let l = distance(w[0], w[1]);
|
||||
if left <= l && l > 0.0 {
|
||||
let t = left / l;
|
||||
return Some([0, 1, 2].map(|k| w[0][k] + t * (w[1][k] - w[0][k])));
|
||||
}
|
||||
left -= l;
|
||||
}
|
||||
self.points.last().copied()
|
||||
}
|
||||
}
|
||||
|
||||
fn distance(a: [f64; 3], b: [f64; 3]) -> f64 {
|
||||
((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2)).sqrt()
|
||||
}
|
||||
|
||||
/// The length-weighted centre of a polyline (its first point when it has no length).
|
||||
fn centre(points: &[[f64; 3]]) -> [f64; 3] {
|
||||
let mut sum = [0.0; 3];
|
||||
let mut weight = 0.0;
|
||||
for w in points.windows(2) {
|
||||
let l = distance(w[0], w[1]);
|
||||
for (k, s) in sum.iter_mut().enumerate() {
|
||||
*s += l * 0.5 * (w[0][k] + w[1][k]);
|
||||
}
|
||||
weight += l;
|
||||
}
|
||||
if weight > 0.0 { sum.map(|s| s / weight) } else { points.first().copied().unwrap_or_default() }
|
||||
}
|
||||
|
||||
/// Number the repeated names `~0`, `~1`, … by position: along the axis their centres spread most
|
||||
/// along, then the other two. Positions are compared on a grid of a millionth of that spread, so
|
||||
/// a tessellation within a different tolerance numbers them the same.
|
||||
fn number_repeats(names: &mut [String], centres: &[[f64; 3]]) {
|
||||
let mut groups: std::collections::BTreeMap<String, Vec<usize>> = std::collections::BTreeMap::new();
|
||||
for (i, n) in names.iter().enumerate() {
|
||||
groups.entry(n.clone()).or_default().push(i);
|
||||
}
|
||||
for (name, mut same) in groups {
|
||||
if same.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
let at = |i: usize| centres.get(i).copied().unwrap_or([0.0; 3]);
|
||||
let mut lo = [f64::INFINITY; 3];
|
||||
let mut hi = [f64::NEG_INFINITY; 3];
|
||||
for c in same.iter().map(|&i| at(i)) {
|
||||
for k in 0..3 {
|
||||
lo[k] = lo[k].min(c[k]);
|
||||
hi[k] = hi[k].max(c[k]);
|
||||
}
|
||||
}
|
||||
let spread = [hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]];
|
||||
let axes = if spread[0] >= spread[1] && spread[0] >= spread[2] {
|
||||
[0, 1, 2]
|
||||
} else if spread[1] >= spread[2] {
|
||||
[1, 2, 0]
|
||||
} else {
|
||||
[2, 0, 1]
|
||||
};
|
||||
let grid = spread.iter().fold(0.0f64, |m, s| m.max(*s)).max(1e-9) * 1e-6;
|
||||
let key = |i: usize| axes.map(|k| (at(i)[k] / grid).round() as i64);
|
||||
same.sort_by_key(|&i| (key(i), i));
|
||||
for (k, i) in same.into_iter().enumerate() {
|
||||
if let Some(slot) = names.get_mut(i) {
|
||||
*slot = format!("{name}~{k}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Shape {
|
||||
/// The name of face `f`: its persistent name, or its index for a shape without names.
|
||||
fn face_label(&self, f: u32) -> String {
|
||||
match self.faces.get(f as usize) {
|
||||
Some(face) if !face.name.is_empty() => face.name.clone(),
|
||||
_ => f.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The persistent names of the edges of `mesh` (a tessellation of this shape), by edge index.
|
||||
pub fn edge_names(&self, mesh: &SurfaceMesh) -> Vec<String> {
|
||||
let mut names: Vec<String> = mesh
|
||||
.edge_faces
|
||||
.iter()
|
||||
.map(|faces| {
|
||||
let mut n: Vec<String> = faces.iter().map(|&f| self.face_label(f)).collect();
|
||||
n.sort();
|
||||
n.join("|")
|
||||
})
|
||||
.collect();
|
||||
names.resize(mesh.edges.len(), String::new());
|
||||
let centres: Vec<[f64; 3]> = mesh.edges.iter().map(|e| centre(e)).collect();
|
||||
number_repeats(&mut names, ¢res);
|
||||
names
|
||||
}
|
||||
|
||||
/// The body's edges with their persistent names, from a tessellation fine enough to place them.
|
||||
pub fn edges(&self) -> Result<Vec<Edge>> {
|
||||
let mesh = self.tessellate((self.size()? * EDGE_TOLERANCE).max(1e-4))?;
|
||||
Ok(self.edges_of(&mesh))
|
||||
}
|
||||
|
||||
/// The edges of `mesh` (a tessellation of this shape) with their persistent names.
|
||||
fn edges_of(&self, mesh: &SurfaceMesh) -> Vec<Edge> {
|
||||
let names = self.edge_names(mesh);
|
||||
names
|
||||
.into_iter()
|
||||
.zip(&mesh.edges)
|
||||
.enumerate()
|
||||
.map(|(i, (name, points))| Edge { name, faces: mesh.edge_faces.get(i).cloned().unwrap_or_default(), points: points.clone() })
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::sample::{self, Plate};
|
||||
use crate::{Cut, open_design};
|
||||
|
||||
fn names(edges: &[super::Edge]) -> Vec<String> {
|
||||
let mut n: Vec<String> = edges.iter().map(|e| e.name.clone()).collect();
|
||||
n.sort();
|
||||
n
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_edge_of_the_plate_has_its_own_name_from_its_faces() {
|
||||
let d = open_design(&sample::plate_design(&Plate::default()).unwrap()).unwrap();
|
||||
let body = &d.bodies[0];
|
||||
let edges = body.edges().unwrap();
|
||||
// A box with a through hole split in two half-cylinders: 12 box edges, 2 × 2 rim arcs and
|
||||
// 2 seams.
|
||||
assert_eq!(edges.len(), 18, "{:?}", names(&edges));
|
||||
let mut unique = names(&edges);
|
||||
unique.dedup();
|
||||
assert_eq!(unique.len(), edges.len(), "{unique:?}");
|
||||
let faces: Vec<&str> = body.faces().iter().map(|f| f.name.as_str()).collect();
|
||||
for e in &edges {
|
||||
let base = e.name.split('~').next().unwrap();
|
||||
assert!(base.split('|').all(|f| faces.contains(&f)), "{} is not named after the faces {faces:?}", e.name);
|
||||
assert!(e.length() > 0.0, "{}", e.name);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edge_names_survive_a_parameter_change_and_a_finer_tessellation() {
|
||||
let a = open_design(&sample::plate_design(&Plate::default()).unwrap()).unwrap();
|
||||
let b = open_design(&sample::plate_design(&Plate { width: 70.0, thickness: 15.0, ..Plate::default() }).unwrap()).unwrap();
|
||||
let (ea, eb) = (a.bodies[0].edges().unwrap(), b.bodies[0].edges().unwrap());
|
||||
assert_eq!(names(&ea), names(&eb));
|
||||
// The through-thickness edges are as long as the plate is thick, before and after.
|
||||
for e in &ea {
|
||||
let other = eb.iter().find(|x| x.name == e.name).unwrap();
|
||||
if (e.length() - 10.0).abs() < 1e-6 {
|
||||
assert!((other.length() - 15.0).abs() < 1e-6, "{}: {}", e.name, other.length());
|
||||
}
|
||||
}
|
||||
let fine = a.bodies[0].tessellate(1e-3).unwrap();
|
||||
let mut n = a.bodies[0].edge_names(&fine);
|
||||
n.sort();
|
||||
assert_eq!(n, names(&ea));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn points_along_an_edge() {
|
||||
let e = super::Edge { name: "e".into(), faces: vec![], points: vec![[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [2.0, 2.0, 0.0]] };
|
||||
assert_eq!(e.point_at(0.0), Some([0.0, 0.0, 0.0]));
|
||||
assert_eq!(e.point_at(0.5), Some([2.0, 0.0, 0.0]));
|
||||
assert_eq!(e.point_at(0.75), Some([2.0, 1.0, 0.0]));
|
||||
assert_eq!(e.point_at(1.0), Some([2.0, 2.0, 0.0]));
|
||||
for bad in [-0.1, 1.5, f64::NAN] {
|
||||
assert_eq!(e.point_at(bad), None);
|
||||
}
|
||||
assert_eq!(super::Edge { points: vec![], ..e }.point_at(0.5), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partition_cut_edges_are_named_after_the_cut_faces() {
|
||||
let d = open_design(&sample::plate_design(&Plate::default()).unwrap()).unwrap();
|
||||
let cut = Cut { name: "Mid".into(), point: [5.0, 15.0, 0.0], normal: [1.0, 0.0, 0.0], bodies: Vec::new() };
|
||||
let p = d.partitioned(&[cut]).unwrap();
|
||||
for (cell, side) in p.bodies.iter().zip(["a", "b"]) {
|
||||
let edges = cell.edges().unwrap();
|
||||
let cut_edges: Vec<&str> = edges.iter().map(|e| e.name.as_str()).filter(|n| n.contains(&format!("partition:Mid:{side}"))).collect();
|
||||
// The cut face is a rectangle: four edges.
|
||||
assert_eq!(cut_edges.len(), 4, "{} {cut_edges:?}", cell.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,11 +18,15 @@
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
mod design;
|
||||
mod edges;
|
||||
pub mod partition;
|
||||
pub mod sample;
|
||||
#[cfg(feature = "scripts")]
|
||||
mod script;
|
||||
|
||||
pub use design::{Design, FeatureError, MAX_DESIGN_BYTES, open_design};
|
||||
pub use edges::{EDGE_TOLERANCE, Edge};
|
||||
pub use partition::{Cut, CutReport};
|
||||
pub mod tagged_mesh;
|
||||
#[cfg(feature = "scripts")]
|
||||
pub use script::{MAX_SCRIPT_BYTES, script_design};
|
||||
@@ -127,6 +131,10 @@ pub struct SurfaceMesh {
|
||||
/// the boundary points they share, accurate to the kernel's linear tolerance, so two copies
|
||||
/// can differ by up to twice it; boundary surface preparation welds at this distance.
|
||||
pub weld_distance: f64,
|
||||
/// The B-rep edges as polylines, by edge index (empty for a surface without B-rep edges).
|
||||
pub edges: Vec<Vec<[f64; 3]>>,
|
||||
/// Per edge: the B-rep faces it bounds (one or two), by face index.
|
||||
pub edge_faces: Vec<Vec<u32>>,
|
||||
}
|
||||
|
||||
fn xyz(v: solidcraft_geom::Vec3) -> [f64; 3] {
|
||||
@@ -152,6 +160,30 @@ impl Shape {
|
||||
self.faces.iter().position(|f| f.name == name).and_then(|i| u32::try_from(i).ok())
|
||||
}
|
||||
|
||||
/// The area centroid of the face with this persistent name, from a tessellation fine enough
|
||||
/// to place it (on a curved face the centroid lies off the surface, inside its curvature).
|
||||
pub fn face_centre(&self, name: &str) -> Result<[f64; 3]> {
|
||||
let face = self.face_index(name).ok_or_else(|| Error::Invalid(format!("body `{}` has no face `{name}`", self.name)))?;
|
||||
let mesh = self.tessellate((self.size()? * edges::EDGE_TOLERANCE).max(1e-4))?;
|
||||
let (mut sum, mut area) = ([0.0; 3], 0.0);
|
||||
for (t, _) in mesh.triangles.iter().zip(&mesh.tri_face).filter(|(_, f)| **f == face) {
|
||||
let corner = |i: u32| mesh.positions.get(i as usize).copied();
|
||||
let (Some(a), Some(b), Some(c)) = (corner(t[0]), corner(t[1]), corner(t[2])) else { continue };
|
||||
let (u, v) = ([0, 1, 2].map(|k| b[k] - a[k]), [0, 1, 2].map(|k| c[k] - a[k]));
|
||||
let n = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]];
|
||||
let w = 0.5 * (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();
|
||||
for (k, s) in sum.iter_mut().enumerate() {
|
||||
*s += w * (a[k] + b[k] + c[k]) / 3.0;
|
||||
}
|
||||
area += w;
|
||||
}
|
||||
if area > 0.0 && area.is_finite() {
|
||||
Ok(sum.map(|s| s / area))
|
||||
} else {
|
||||
Err(Error::Failed(format!("face `{name}` of body `{}` has no area", self.name)))
|
||||
}
|
||||
}
|
||||
|
||||
/// The analytic surface of each B-rep face, by face index (the [`SurfaceMesh::tri_face`]
|
||||
/// tags): `None` for a free-form face. Meshers project nodes onto these surfaces.
|
||||
pub fn face_surfaces(&self) -> Result<Vec<Option<FaceSurface>>> {
|
||||
@@ -206,6 +238,8 @@ impl Shape {
|
||||
triangles: m.triangles,
|
||||
tri_face: m.tri_face,
|
||||
weld_distance: 2.0 * LINEAR_TOLERANCE,
|
||||
edges: m.edges.into_iter().map(|e| e.into_iter().map(xyz).collect()).collect(),
|
||||
edge_faces: m.edge_faces,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -231,6 +265,22 @@ impl SurfaceMesh {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The plate's side face at x = 0 (40 × 30 × 10, the hole well inside) has its centre in its
|
||||
/// middle; an unknown face is an error.
|
||||
#[test]
|
||||
fn a_face_centre_is_its_area_centroid() {
|
||||
let d = open_design(&sample::plate_design(&sample::Plate::default()).unwrap()).unwrap();
|
||||
let body = &d.bodies[0];
|
||||
let surfaces = body.face_surfaces().unwrap();
|
||||
let side = surfaces
|
||||
.iter()
|
||||
.position(|s| matches!(s, Some(FaceSurface::Plane { normal, point }) if normal[0] < -0.5 && point[0].abs() < 1e-9))
|
||||
.unwrap();
|
||||
let c = body.face_centre(&body.faces()[side].name).unwrap();
|
||||
assert!((c[0]).abs() < 1e-9 && (c[1] - 15.0).abs() < 1e-6 && (c[2] - 5.0).abs() < 1e-6, "{c:?}");
|
||||
assert!(body.face_centre("nope").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_measures() {
|
||||
let m = block([0., 0., 0.], [10., 20., 30.]).unwrap().measure().unwrap();
|
||||
|
||||
@@ -0,0 +1,501 @@
|
||||
//! Partitions: a design's bodies cut into cells by planes, for meshing cell by cell.
|
||||
//!
|
||||
//! A partition cuts bodies of the open design by a plane with SolidCraft's kernel
|
||||
//! (`split_by_plane`, the operation behind SolidCraft's split body), in memory: the design file is
|
||||
//! never changed. The partitions live in the FieldCraft model and are applied again, in order,
|
||||
//! whenever the design is opened, so an edit of the design followed by a re-open replays them.
|
||||
//!
|
||||
//! Names are FieldCraft's own, so they do not depend on the order of the design's timeline:
|
||||
//! - **Cells.** A body cut by a plane gives `<body>/a` (the piece on the plane's negative side)
|
||||
//! and `<body>/b`; several disjoint pieces on one side are `<body>/a1`, `<body>/a2`, … ordered
|
||||
//! by centroid.
|
||||
//! - **Cut faces** pair across the cut: on a cell on the negative side (its outward normal along
|
||||
//! the plane's normal) the face is `partition:<name>:a`, on the positive side
|
||||
//! `partition:<name>:b`. Several disjoint faces on one cell (a cut through a hole) are `…#0`,
|
||||
//! `…#1`, ordered along the plane, which a set naming `partition:<name>:a` selects together.
|
||||
//! - **Every other face** inherits the persistent name of the face it is a piece of (found on the
|
||||
//! same surface under a point of the piece). Where a cell has several pieces of one face they
|
||||
//! are `<name>#0`, `<name>#1`, …, which sets naming `<name>` select.
|
||||
|
||||
use solidcraft_geom::{Plane, Vec3};
|
||||
use solidcraft_kernel::guard;
|
||||
|
||||
use crate::{Design, Error, Face, FaceSurface, FeatureError, Result, Shape, SurfaceMesh};
|
||||
|
||||
/// Most partitions a design takes.
|
||||
pub const MAX_CUTS: usize = 256;
|
||||
/// Most cells the partitions make in all.
|
||||
pub const MAX_CELLS: usize = 4096;
|
||||
/// A cut face lies on the plane within this fraction of its body's size.
|
||||
const ON_PLANE: f64 = 1e-6;
|
||||
/// Tessellation tolerance (fraction of a body's size) for matching and ordering faces.
|
||||
const MATCH_TOLERANCE: f64 = 2e-3;
|
||||
|
||||
/// One partition: the bodies it cuts by a plane.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Cut {
|
||||
/// Names the cut faces (`partition:<name>:a|b`).
|
||||
pub name: String,
|
||||
/// A point on the plane and its normal (any length but zero).
|
||||
pub point: [f64; 3],
|
||||
pub normal: [f64; 3],
|
||||
/// The bodies to cut, by name, as they are when this partition comes (the cells of earlier
|
||||
/// partitions included); empty: every body the plane divides.
|
||||
pub bodies: Vec<String>,
|
||||
}
|
||||
|
||||
/// What a partition did.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CutReport {
|
||||
pub name: String,
|
||||
/// The bodies it cut, each into two or more cells.
|
||||
pub split: Vec<String>,
|
||||
/// How many cut faces it named.
|
||||
pub faces: usize,
|
||||
}
|
||||
|
||||
fn vec3(p: [f64; 3]) -> Vec3 {
|
||||
Vec3 { x: p[0], y: p[1], z: p[2] }
|
||||
}
|
||||
|
||||
fn dot(a: [f64; 3], b: [f64; 3]) -> f64 {
|
||||
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
|
||||
}
|
||||
|
||||
fn sub(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
|
||||
[a[0] - b[0], a[1] - b[1], a[2] - b[2]]
|
||||
}
|
||||
|
||||
fn cross(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
|
||||
[a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
|
||||
}
|
||||
|
||||
fn lexical(a: &[f64; 3], b: &[f64; 3]) -> std::cmp::Ordering {
|
||||
a.iter().zip(b).map(|(x, y)| x.total_cmp(y)).find(|o| o.is_ne()).unwrap_or(std::cmp::Ordering::Equal)
|
||||
}
|
||||
|
||||
/// The plane of a cut, with its unit normal.
|
||||
fn plane_of(cut: &Cut) -> Result<(Plane, [f64; 3])> {
|
||||
let finite = cut.point.iter().chain(&cut.normal).all(|v| v.is_finite() && v.abs() <= 1e9);
|
||||
let len = dot(cut.normal, cut.normal).sqrt();
|
||||
if !finite || !(len > 1e-12) {
|
||||
return Err(Error::Invalid(format!("partition `{}`: the plane needs a finite point and a non-zero normal", cut.name)));
|
||||
}
|
||||
let n = cut.normal.map(|v| v / len);
|
||||
let plane = Plane::from_normal(vec3(cut.point), vec3(n))
|
||||
.ok_or_else(|| Error::Invalid(format!("partition `{}`: the plane needs a non-zero normal", cut.name)))?;
|
||||
Ok((plane, n))
|
||||
}
|
||||
|
||||
impl Design {
|
||||
/// The design as opened, cut by `cuts` in order (the partitions replace any applied before).
|
||||
/// A cut that names a body the design does not have, or that does not divide a body it
|
||||
/// names, is listed in [`Design::errors`] (feature `partition <name>`), as a feature of the
|
||||
/// design that failed to rebuild; the rest still apply.
|
||||
pub fn partitioned(&self, cuts: &[Cut]) -> Result<Design> {
|
||||
if cuts.len() > MAX_CUTS {
|
||||
return Err(Error::Invalid(format!("a design takes at most {MAX_CUTS} partitions")));
|
||||
}
|
||||
let planes: Vec<(Plane, [f64; 3])> = cuts.iter().map(plane_of).collect::<Result<_>>()?;
|
||||
let mut bodies: Vec<Shape> = self.source.as_ref().clone();
|
||||
let mut errors: Vec<FeatureError> = self.errors.iter().filter(|e| !e.feature.starts_with("partition ")).cloned().collect();
|
||||
let mut reports = Vec::with_capacity(cuts.len());
|
||||
for (cut, (plane, n)) in cuts.iter().zip(&planes) {
|
||||
let feature = format!("partition {}", cut.name);
|
||||
for b in &cut.bodies {
|
||||
if !bodies.iter().any(|x| &x.name == b) {
|
||||
errors.push(FeatureError { feature: feature.clone(), message: format!("no body `{b}` to cut") });
|
||||
}
|
||||
}
|
||||
let mut report = CutReport { name: cut.name.clone(), split: Vec::new(), faces: 0 };
|
||||
let mut next = Vec::with_capacity(bodies.len() + 1);
|
||||
for body in bodies {
|
||||
let listed = cut.bodies.iter().any(|b| b == &body.name);
|
||||
if !(cut.bodies.is_empty() || listed) {
|
||||
next.push(body);
|
||||
continue;
|
||||
}
|
||||
match split(&body, plane, *n, cut)? {
|
||||
Some((cells, faces)) => {
|
||||
report.split.push(body.name.clone());
|
||||
report.faces += faces;
|
||||
next.extend(cells);
|
||||
}
|
||||
None => {
|
||||
if listed {
|
||||
errors.push(FeatureError { feature: feature.clone(), message: format!("the plane does not divide `{}`", body.name) });
|
||||
}
|
||||
next.push(body);
|
||||
}
|
||||
}
|
||||
if next.len() > MAX_CELLS {
|
||||
return Err(Error::Invalid(format!("the partitions make at most {MAX_CELLS} cells")));
|
||||
}
|
||||
}
|
||||
bodies = next;
|
||||
reports.push(report);
|
||||
}
|
||||
Ok(Design { name: self.name.clone(), bodies, errors, cuts: reports, source: std::sync::Arc::clone(&self.source) })
|
||||
}
|
||||
}
|
||||
|
||||
/// Cut one body: its cells, named, and how many cut faces they have; `None` when the plane does
|
||||
/// not divide it.
|
||||
fn split(body: &Shape, plane: &Plane, n: [f64; 3], cut: &Cut) -> Result<Option<(Vec<Shape>, usize)>> {
|
||||
let parts = match guard("partition", || solidcraft_kernel::split_by_plane(&body.body, plane)) {
|
||||
Ok(p) if p.len() >= 2 => p,
|
||||
_ => return Ok(None),
|
||||
};
|
||||
let size = body.size()?;
|
||||
let tol = (MATCH_TOLERANCE * size).max(1e-4);
|
||||
let parent = Faces::of(body, tol)?;
|
||||
let mut cells: Vec<(bool, [f64; 3], Shape)> = Vec::with_capacity(parts.len());
|
||||
for part in parts {
|
||||
let mut shape = Shape { name: String::new(), body: part, faces: Vec::new() };
|
||||
let m = shape.measure()?;
|
||||
let negative = dot(sub(m.centroid, cut.point), n) < 0.0;
|
||||
shape.faces = (0..m.faces).map(|_| Face { name: String::new(), exact: false }).collect();
|
||||
cells.push((negative, m.centroid, shape));
|
||||
}
|
||||
cells.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| lexical(&a.1, &b.1)));
|
||||
let mut faces = 0;
|
||||
let count = |neg: bool| cells.iter().filter(|c| c.0 == neg).count();
|
||||
let (na, nb) = (count(true), count(false));
|
||||
let (mut ka, mut kb) = (0, 0);
|
||||
let mut out = Vec::with_capacity(cells.len());
|
||||
for (negative, _, mut shape) in cells {
|
||||
let (k, of) = if negative {
|
||||
ka += 1;
|
||||
(ka, na)
|
||||
} else {
|
||||
kb += 1;
|
||||
(kb, nb)
|
||||
};
|
||||
let side = if negative { "a" } else { "b" };
|
||||
shape.name = if of > 1 { format!("{}/{side}{k}", body.name) } else { format!("{}/{side}", body.name) };
|
||||
faces += name_faces(&mut shape, &parent, cut, n, size, tol)?;
|
||||
out.push(shape);
|
||||
}
|
||||
Ok(Some((out, faces)))
|
||||
}
|
||||
|
||||
/// A body's faces as matching needs them: each face's analytic surface, name and triangles.
|
||||
struct Faces {
|
||||
surfaces: Vec<Option<FaceSurface>>,
|
||||
names: Vec<Face>,
|
||||
mesh: SurfaceMesh,
|
||||
}
|
||||
|
||||
impl Faces {
|
||||
fn of(body: &Shape, tol: f64) -> Result<Faces> {
|
||||
Ok(Faces { surfaces: body.face_surfaces()?, names: body.faces.clone(), mesh: body.tessellate(tol)? })
|
||||
}
|
||||
|
||||
/// The face nearest to `p` (by distance to its triangles), among those `keep` allows.
|
||||
fn nearest(&self, p: [f64; 3], keep: impl Fn(usize) -> bool) -> Option<usize> {
|
||||
let mut best: Option<(f64, usize)> = None;
|
||||
for (t, &f) in self.mesh.triangles.iter().zip(&self.mesh.tri_face) {
|
||||
let f = f as usize;
|
||||
if !keep(f) {
|
||||
continue;
|
||||
}
|
||||
let q = |k: usize| t.get(k).and_then(|&i| self.mesh.positions.get(i as usize)).copied().unwrap_or([0.0; 3]);
|
||||
let d = point_triangle(p, q(0), q(1), q(2));
|
||||
if best.is_none_or(|(b, _)| d < b) {
|
||||
best = Some((d, f));
|
||||
}
|
||||
}
|
||||
best.map(|(_, f)| f)
|
||||
}
|
||||
}
|
||||
|
||||
impl Shape {
|
||||
/// For each point, the face (by index, the [`SurfaceMesh::tri_face`] tag) nearest to it,
|
||||
/// measured to a tessellation within `tolerance`; `None` for a body without faces.
|
||||
pub fn nearest_faces(&self, points: &[[f64; 3]], tolerance: f64) -> Result<Vec<Option<u32>>> {
|
||||
let faces = Faces { surfaces: Vec::new(), names: Vec::new(), mesh: self.tessellate(tolerance)? };
|
||||
Ok(points.iter().map(|p| faces.nearest(*p, |_| true).and_then(|f| u32::try_from(f).ok())).collect())
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether two analytic surfaces are the same surface (within `tol`); free-form faces match any
|
||||
/// free-form face.
|
||||
fn same_surface(a: Option<FaceSurface>, b: Option<FaceSurface>, tol: f64) -> bool {
|
||||
let close = |x: [f64; 3], y: [f64; 3]| dot(sub(x, y), sub(x, y)).sqrt() <= tol;
|
||||
let parallel = |x: [f64; 3], y: [f64; 3]| dot(cross(x, y), cross(x, y)).sqrt() <= 1e-6;
|
||||
let on_line = |p: [f64; 3], o: [f64; 3], axis: [f64; 3]| {
|
||||
let c = cross(sub(p, o), axis);
|
||||
dot(c, c).sqrt() <= tol
|
||||
};
|
||||
match (a, b) {
|
||||
(None, None) => true,
|
||||
(Some(FaceSurface::Plane { normal: n1, point: p1 }), Some(FaceSurface::Plane { normal: n2, point: p2 })) => {
|
||||
dot(n1, n2) > 1.0 - 1e-9 && dot(sub(p2, p1), n1).abs() <= tol
|
||||
}
|
||||
(Some(FaceSurface::Cylinder { origin: o1, axis: a1, radius: r1 }), Some(FaceSurface::Cylinder { origin: o2, axis: a2, radius: r2 })) => {
|
||||
(r1 - r2).abs() <= tol && parallel(a1, a2) && on_line(o2, o1, a1)
|
||||
}
|
||||
(Some(FaceSurface::Cone { apex: p1, axis: a1, half_angle: h1 }), Some(FaceSurface::Cone { apex: p2, axis: a2, half_angle: h2 })) => {
|
||||
close(p1, p2) && dot(a1, a2) > 1.0 - 1e-9 && (h1 - h2).abs() <= 1e-9
|
||||
}
|
||||
(Some(FaceSurface::Sphere { center: c1, radius: r1 }), Some(FaceSurface::Sphere { center: c2, radius: r2 })) => {
|
||||
close(c1, c2) && (r1 - r2).abs() <= tol
|
||||
}
|
||||
(
|
||||
Some(FaceSurface::Torus { center: c1, axis: a1, major: m1, minor: n1 }),
|
||||
Some(FaceSurface::Torus { center: c2, axis: a2, major: m2, minor: n2 }),
|
||||
) => close(c1, c2) && parallel(a1, a2) && (m1 - m2).abs() <= tol && (n1 - n2).abs() <= tol,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The distance from `p` to the triangle `a b c` (Ericson, Real-Time Collision Detection §5.1.5).
|
||||
fn point_triangle(p: [f64; 3], a: [f64; 3], b: [f64; 3], c: [f64; 3]) -> f64 {
|
||||
let (ab, ac, ap) = (sub(b, a), sub(c, a), sub(p, a));
|
||||
let (d1, d2) = (dot(ab, ap), dot(ac, ap));
|
||||
let at = |q: [f64; 3]| dot(sub(p, q), sub(p, q)).sqrt();
|
||||
let lerp = |o: [f64; 3], d: [f64; 3], t: f64| [o[0] + d[0] * t, o[1] + d[1] * t, o[2] + d[2] * t];
|
||||
if d1 <= 0.0 && d2 <= 0.0 {
|
||||
return at(a);
|
||||
}
|
||||
let bp = sub(p, b);
|
||||
let (d3, d4) = (dot(ab, bp), dot(ac, bp));
|
||||
if d3 >= 0.0 && d4 <= d3 {
|
||||
return at(b);
|
||||
}
|
||||
let vc = d1 * d4 - d3 * d2;
|
||||
if vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0 {
|
||||
return at(lerp(a, ab, d1 / (d1 - d3)));
|
||||
}
|
||||
let cp = sub(p, c);
|
||||
let (d5, d6) = (dot(ab, cp), dot(ac, cp));
|
||||
if d6 >= 0.0 && d5 <= d6 {
|
||||
return at(c);
|
||||
}
|
||||
let vb = d5 * d2 - d1 * d6;
|
||||
if vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0 {
|
||||
return at(lerp(a, ac, d2 / (d2 - d6)));
|
||||
}
|
||||
let va = d3 * d6 - d5 * d4;
|
||||
if va <= 0.0 && (d4 - d3) >= 0.0 && (d5 - d6) >= 0.0 {
|
||||
return at(lerp(b, sub(c, b), (d4 - d3) / ((d4 - d3) + (d5 - d6))));
|
||||
}
|
||||
let denom = va + vb + vc;
|
||||
if denom.abs() < f64::MIN_POSITIVE {
|
||||
return at(a);
|
||||
}
|
||||
let (v, w) = (vb / denom, vc / denom);
|
||||
at([a[0] + ab[0] * v + ac[0] * w, a[1] + ab[1] * v + ac[1] * w, a[2] + ab[2] * v + ac[2] * w])
|
||||
}
|
||||
|
||||
/// The name without a trailing piece number (`F2:top#1` → `F2:top`).
|
||||
fn base_name(name: &str) -> &str {
|
||||
match name.rsplit_once('#') {
|
||||
Some((b, k)) if !k.is_empty() && k.bytes().all(|c| c.is_ascii_digit()) => b,
|
||||
_ => name,
|
||||
}
|
||||
}
|
||||
|
||||
/// Name a cell's faces: cut faces after the cut, the rest after the face of `parent` they are a
|
||||
/// piece of. Returns how many cut faces it has.
|
||||
fn name_faces(cell: &mut Shape, parent: &Faces, cut: &Cut, n: [f64; 3], size: f64, tol: f64) -> Result<usize> {
|
||||
let own = Faces::of(cell, tol)?;
|
||||
// A point on each face (the centroid of its largest triangle) and its area-weighted centroid.
|
||||
let count = cell.faces.len();
|
||||
let mut probe = vec![(0.0f64, [0.0; 3]); count];
|
||||
let mut centroid = vec![([0.0; 3], 0.0f64); count];
|
||||
for (t, &f) in own.mesh.triangles.iter().zip(&own.mesh.tri_face) {
|
||||
let q = |k: usize| t.get(k).and_then(|&i| own.mesh.positions.get(i as usize)).copied().unwrap_or([0.0; 3]);
|
||||
let (a, b, c) = (q(0), q(1), q(2));
|
||||
let cr = cross(sub(b, a), sub(c, a));
|
||||
let area = 0.5 * dot(cr, cr).sqrt();
|
||||
let mid = [(a[0] + b[0] + c[0]) / 3.0, (a[1] + b[1] + c[1]) / 3.0, (a[2] + b[2] + c[2]) / 3.0];
|
||||
if let Some(slot) = probe.get_mut(f as usize).filter(|s| area > s.0) {
|
||||
*slot = (area, mid);
|
||||
}
|
||||
if let Some((s, w)) = centroid.get_mut(f as usize) {
|
||||
for k in 0..3 {
|
||||
s[k] += area * mid[k];
|
||||
}
|
||||
*w += area;
|
||||
}
|
||||
}
|
||||
let centroid: Vec<[f64; 3]> = centroid.into_iter().map(|(s, w)| if w > 0.0 { s.map(|x| x / w) } else { s }).collect();
|
||||
let on_plane = ON_PLANE * size.max(1.0);
|
||||
let mut names: Vec<(String, bool)> = Vec::with_capacity(count); // (name, exact)
|
||||
let mut cut_faces = 0;
|
||||
for i in 0..count {
|
||||
let surface = own.surfaces.get(i).copied().flatten();
|
||||
if let Some(FaceSurface::Plane { normal, point }) = surface {
|
||||
let along = dot(normal, n);
|
||||
if (along.abs() - 1.0).abs() < 1e-9 && dot(sub(point, cut.point), n).abs() < on_plane.max(tol * 1e-3) {
|
||||
// Outward along the normal: the cell is on the negative side.
|
||||
let side = if along > 0.0 { "a" } else { "b" };
|
||||
names.push((format!("partition:{}:{side}", cut.name), true));
|
||||
cut_faces += 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let p = probe.get(i).map_or([0.0; 3], |x| x.1);
|
||||
let from =
|
||||
parent.nearest(p, |f| same_surface(surface, parent.surfaces.get(f).copied().flatten(), tol)).or_else(|| parent.nearest(p, |_| true));
|
||||
let face = from.and_then(|f| parent.names.get(f));
|
||||
names.push(match face {
|
||||
Some(f) if !f.name.is_empty() => (f.name.clone(), f.exact),
|
||||
_ => (i.to_string(), false),
|
||||
});
|
||||
}
|
||||
// Several pieces of one face on the cell: numbered by position.
|
||||
let mut order: Vec<usize> = (0..count).collect();
|
||||
order.sort_by(|&a, &b| lexical(centroid.get(a).unwrap_or(&[0.0; 3]), centroid.get(b).unwrap_or(&[0.0; 3])));
|
||||
let bases: Vec<String> = names.iter().map(|(nm, _)| base_name(nm).to_string()).collect();
|
||||
let mut numbered = vec![None; count];
|
||||
for (i, base) in bases.iter().enumerate() {
|
||||
if numbered.get(i).is_some_and(Option::is_some) {
|
||||
continue;
|
||||
}
|
||||
let group: Vec<usize> = order.iter().copied().filter(|&j| bases.get(j) == Some(base)).collect();
|
||||
// Untouched pieces keep the numbers SolidCraft gave them; pieces the cut made (or a
|
||||
// name two pieces now share) are numbered again.
|
||||
let distinct = {
|
||||
let mut v: Vec<&str> = group.iter().filter_map(|&j| names.get(j).map(|x| x.0.as_str())).collect();
|
||||
v.sort_unstable();
|
||||
v.dedup();
|
||||
v.len() == group.len()
|
||||
};
|
||||
for (k, &j) in group.iter().enumerate() {
|
||||
if let Some(slot) = numbered.get_mut(j) {
|
||||
*slot = Some(if distinct { names.get(j).map(|x| x.0.clone()).unwrap_or_default() } else { format!("{base}#{k}") });
|
||||
}
|
||||
}
|
||||
}
|
||||
for ((face, name), (_, exact)) in cell.faces.iter_mut().zip(numbered).zip(&names) {
|
||||
face.name = name.unwrap_or_default();
|
||||
face.exact = *exact;
|
||||
}
|
||||
Ok(cut_faces)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::open_design;
|
||||
use crate::sample::{self, Plate};
|
||||
|
||||
fn plate() -> Design {
|
||||
open_design(&sample::plate_design(&Plate::default()).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn cut(name: &str, point: [f64; 3], normal: [f64; 3]) -> Cut {
|
||||
Cut { name: name.into(), point, normal, bodies: Vec::new() }
|
||||
}
|
||||
|
||||
fn names(b: &Shape) -> Vec<&str> {
|
||||
b.faces().iter().map(|f| f.name.as_str()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plane_cuts_the_plate_into_cells_with_paired_cut_faces() {
|
||||
let d = plate();
|
||||
let whole = d.bodies[0].measure().unwrap().volume;
|
||||
// Through the hole's centre (x = 15): each half has two cut faces, either side of the hole.
|
||||
let p = d.partitioned(&[cut("Mid", [15.0, 0.0, 0.0], [1.0, 0.0, 0.0])]).unwrap();
|
||||
assert!(p.errors.is_empty(), "{:?}", p.errors);
|
||||
assert_eq!(p.bodies.len(), 2, "{:?}", p.bodies.iter().map(|b| &b.name).collect::<Vec<_>>());
|
||||
let volume: f64 = p.bodies.iter().map(|b| b.measure().unwrap().volume).sum();
|
||||
assert!((volume - whole).abs() < 1e-6 * whole, "{volume} vs {whole}");
|
||||
assert_eq!(p.cuts, vec![CutReport { name: "Mid".into(), split: vec![d.bodies[0].name.clone()], faces: 4 }]);
|
||||
let mut sides = Vec::new();
|
||||
for b in &p.bodies {
|
||||
let m = b.measure().unwrap();
|
||||
let side = if m.centroid[0] < 15.0 { "a" } else { "b" };
|
||||
let mut cut: Vec<&str> = names(b).into_iter().filter(|n| n.starts_with("partition:")).collect();
|
||||
cut.sort_unstable();
|
||||
assert_eq!(cut, vec![format!("partition:Mid:{side}#0"), format!("partition:Mid:{side}#1")], "{:?}", names(b));
|
||||
sides.push(side);
|
||||
}
|
||||
sides.sort_unstable();
|
||||
assert_eq!(sides, ["a", "b"]);
|
||||
// Faces the cut did not touch keep their names; the cut's faces pair by index (#0 with
|
||||
// #0) and lie on the same piece of the plane.
|
||||
let original: Vec<&str> = names(&d.bodies[0]).into_iter().map(base_name).collect();
|
||||
let body = &d.bodies[0].name;
|
||||
let mut cells: Vec<&str> = p.bodies.iter().map(|b| b.name.as_str()).collect();
|
||||
cells.sort_unstable();
|
||||
assert_eq!(cells, [format!("{body}/a"), format!("{body}/b")]);
|
||||
for b in &p.bodies {
|
||||
let n = names(b);
|
||||
assert!(n.iter().filter(|n| !n.starts_with("partition:")).all(|n| original.contains(&base_name(n))), "{n:?} {original:?}");
|
||||
assert!(b.faces().iter().all(|f| f.exact), "{:?}", b.faces());
|
||||
let mut unique = n.clone();
|
||||
unique.sort_unstable();
|
||||
unique.dedup();
|
||||
assert_eq!(unique.len(), n.len(), "{n:?}");
|
||||
}
|
||||
// The cut is replayed from the design as opened: partitioning again replaces it.
|
||||
let again = p.partitioned(&[]).unwrap();
|
||||
assert_eq!(again.bodies.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cuts_follow_each_other_and_name_only_the_bodies_they_divide() {
|
||||
let d = plate();
|
||||
let p = d.partitioned(&[cut("X", [30.0, 0.0, 0.0], [1.0, 0.0, 0.0]), cut("Z", [0.0, 0.0, 5.0], [0.0, 0.0, -1.0])]).unwrap();
|
||||
assert!(p.errors.is_empty(), "{:?}", p.errors);
|
||||
assert_eq!(p.bodies.len(), 4);
|
||||
assert_eq!(p.cuts.len(), 2);
|
||||
assert_eq!(p.cuts[1].split.len(), 2);
|
||||
for b in &p.bodies {
|
||||
let n = names(b);
|
||||
assert_eq!(n.iter().filter(|n| n.starts_with("partition:X:")).count(), 1, "{n:?}");
|
||||
assert_eq!(n.iter().filter(|n| n.starts_with("partition:Z:")).count(), 1, "{n:?}");
|
||||
// The normal points down: the cell above z = 5 is on its negative side.
|
||||
let above = b.measure().unwrap().centroid[2] > 5.0;
|
||||
assert!(n.contains(&if above { "partition:Z:a" } else { "partition:Z:b" }), "{n:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plane_that_misses_or_a_missing_body_is_reported_not_fatal() {
|
||||
let d = plate();
|
||||
let body = d.bodies[0].name.clone();
|
||||
let miss = Cut { bodies: vec![body.clone()], ..cut("Out", [100.0, 0.0, 0.0], [1.0, 0.0, 0.0]) };
|
||||
let gone = Cut { bodies: vec!["Nope".into()], ..cut("Gone", [10.0, 0.0, 0.0], [1.0, 0.0, 0.0]) };
|
||||
let p = d.partitioned(&[miss, gone, cut("Free", [100.0, 0.0, 0.0], [1.0, 0.0, 0.0])]).unwrap();
|
||||
assert_eq!(p.bodies.len(), 1);
|
||||
let features: Vec<&str> = p.errors.iter().map(|e| e.feature.as_str()).collect();
|
||||
assert_eq!(features, ["partition Out", "partition Gone"], "{:?}", p.errors);
|
||||
assert_eq!(p.bodies[0].name, body);
|
||||
assert!(p.cuts.iter().all(|c| c.split.is_empty() && c.faces == 0), "{:?}", p.cuts);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_nearest_face_of_a_point() {
|
||||
let d = plate();
|
||||
let b = &d.bodies[0];
|
||||
// Above the top (z = 10) and beside the side at y = 0.
|
||||
let f = b.nearest_faces(&[[30.0, 20.0, 10.5], [30.0, -0.5, 5.0]], 0.05).unwrap();
|
||||
let surfaces = b.face_surfaces().unwrap();
|
||||
let normal = |f: Option<u32>| match surfaces[f.unwrap() as usize] {
|
||||
Some(FaceSurface::Plane { normal, .. }) => normal,
|
||||
s => panic!("{s:?}"),
|
||||
};
|
||||
assert!((normal(f[0])[2] - 1.0).abs() < 1e-12);
|
||||
assert!((normal(f[1])[1] + 1.0).abs() < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_planes_are_an_error() {
|
||||
let d = plate();
|
||||
for (point, normal) in [
|
||||
([0.0; 3], [0.0; 3]),
|
||||
([f64::NAN, 0.0, 0.0], [1.0, 0.0, 0.0]),
|
||||
([0.0; 3], [f64::INFINITY, 0.0, 0.0]),
|
||||
([1e300, 0.0, 0.0], [1.0, 0.0, 0.0]),
|
||||
] {
|
||||
assert!(d.partitioned(&[cut("Bad", point, normal)]).is_err(), "{point:?} {normal:?}");
|
||||
}
|
||||
let many = vec![cut("M", [1.0, 0.0, 0.0], [1.0, 0.0, 0.0]); MAX_CUTS + 1];
|
||||
assert!(d.partitioned(&many).is_err());
|
||||
}
|
||||
}
|
||||
@@ -50,6 +50,7 @@ fn extrude(sketch: u64, distance: &str, operation: Operation) -> FeatureKind {
|
||||
},
|
||||
operation,
|
||||
targets: vec![],
|
||||
thin: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -341,7 +341,11 @@ fn surface(mut o: Object, k: usize, id: u32, xf: &Xf, unit: f64) -> Result<Tagge
|
||||
}
|
||||
let faces = o.faces.unwrap_or_else(|| o.tags.iter().max().map_or(1, |f| f.saturating_add(1)));
|
||||
let name = if o.name.is_empty() { format!("Mesh{}", k + 1) } else { o.name };
|
||||
Ok(TaggedSurface { name, mesh: SurfaceMesh { positions: o.positions, triangles: o.triangles, tri_face: o.tags, weld_distance: 0.0 }, faces })
|
||||
Ok(TaggedSurface {
|
||||
name,
|
||||
mesh: SurfaceMesh { positions: o.positions, triangles: o.triangles, tri_face: o.tags, weld_distance: 0.0, ..SurfaceMesh::default() },
|
||||
faces,
|
||||
})
|
||||
}
|
||||
|
||||
/// The surfaces of a 3MF package, one per build item, in millimetres.
|
||||
@@ -475,8 +479,8 @@ mod tests {
|
||||
assert_eq!(bytes, write_tagged(&[("Block", &mesh, faces), ("Again", &mesh, faces)]), "deterministic bytes");
|
||||
let got = read_3mf(&bytes).unwrap();
|
||||
assert_eq!(got.len(), 2);
|
||||
// The file carries no weld distance.
|
||||
let mesh = SurfaceMesh { weld_distance: 0.0, ..mesh };
|
||||
// The file carries no weld distance and no B-rep edges.
|
||||
let mesh = SurfaceMesh { weld_distance: 0.0, edges: Vec::new(), edge_faces: Vec::new(), ..mesh };
|
||||
assert_eq!(got[0], TaggedSurface { name: "Block".into(), mesh: mesh.clone(), faces: 6 });
|
||||
assert_eq!(got[1].name, "Again");
|
||||
assert_eq!(got[1].mesh, mesh);
|
||||
@@ -574,7 +578,13 @@ mod tests {
|
||||
assert!(read_3mf(b"PK\x03\x04garbage").is_err());
|
||||
let good = write_tagged(&[(
|
||||
"T",
|
||||
&SurfaceMesh { positions: vec![[0.0; 3]; 3], triangles: vec![[0, 1, 2]], tri_face: vec![0], weld_distance: 0.0 },
|
||||
&SurfaceMesh {
|
||||
positions: vec![[0.0; 3]; 3],
|
||||
triangles: vec![[0, 1, 2]],
|
||||
tri_face: vec![0],
|
||||
weld_distance: 0.0,
|
||||
..SurfaceMesh::default()
|
||||
},
|
||||
1,
|
||||
)]);
|
||||
for cut in [10, good.len() / 2, good.len() - 1] {
|
||||
|
||||
@@ -63,6 +63,11 @@ mod browser {
|
||||
FILES.with(|f| f.borrow().list(dir))
|
||||
}
|
||||
|
||||
/// Files in memory keep no modification time.
|
||||
pub fn modified(_path: &Path) -> Option<u64> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Folders are implied by the files' paths.
|
||||
pub fn create_dir_all(_dir: &Path) -> Result<()> {
|
||||
Ok(())
|
||||
@@ -228,6 +233,12 @@ mod disk {
|
||||
fs::create_dir_all(dir).map_err(|e| io_error(dir, e))
|
||||
}
|
||||
|
||||
/// When a regular file was last modified (seconds since 1970), if the platform says.
|
||||
pub fn modified(path: &Path) -> Option<u64> {
|
||||
let meta = fs::metadata(path).ok().filter(fs::Metadata::is_file)?;
|
||||
meta.modified().ok()?.duration_since(std::time::UNIX_EPOCH).ok().map(|d| d.as_secs())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
//!
|
||||
//! - `fieldcraft.json`: the manifest. The format tag (`fieldcraft/1`), the program that wrote
|
||||
//! it, the geometry the model is built on (the SolidCraft design and the imported 3MF meshes,
|
||||
//! each a path and the SHA-256 of its content, opened again when the model is), and the size
|
||||
//! and SHA-256 of every other part.
|
||||
//! each a path and the SHA-256 of its content, opened again when the model is), the view state
|
||||
//! ([`View`]: what the viewport hides), and the size and SHA-256 of every other part.
|
||||
//! - `model.json`: the model definition (unit system, sets, materials, sections, reference
|
||||
//! points, couplings, boundary conditions, loads, steps) as pretty-printed JSON with a stable
|
||||
//! key order, so two versions of a model diff line by line.
|
||||
@@ -28,7 +28,7 @@ pub mod mesh;
|
||||
pub mod recovery;
|
||||
pub mod roots;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::io::{Cursor, Read, Write};
|
||||
|
||||
use fieldcraft_model::Model;
|
||||
@@ -176,6 +176,75 @@ pub struct Geometry {
|
||||
pub meshes: Vec<SourceFile>,
|
||||
}
|
||||
|
||||
/// Most items a view hides.
|
||||
pub const MAX_HIDDEN: usize = 100_000;
|
||||
|
||||
/// Longest name of a hidden item.
|
||||
const MAX_HIDDEN_NAME: usize = 1024;
|
||||
|
||||
/// The kinds of items the viewport draws one by one, and so can hide.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ItemKind {
|
||||
/// A body of the open design (or a cell of a partitioned one).
|
||||
Body,
|
||||
/// An imported surface.
|
||||
Surface,
|
||||
Datum,
|
||||
BoundaryCondition,
|
||||
Load,
|
||||
ReferencePoint,
|
||||
Coupling,
|
||||
}
|
||||
|
||||
impl ItemKind {
|
||||
pub const ALL: [ItemKind; 7] = [
|
||||
ItemKind::Body,
|
||||
ItemKind::Surface,
|
||||
ItemKind::Datum,
|
||||
ItemKind::BoundaryCondition,
|
||||
ItemKind::Load,
|
||||
ItemKind::ReferencePoint,
|
||||
ItemKind::Coupling,
|
||||
];
|
||||
}
|
||||
|
||||
/// An item of the viewport, by kind and name.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Item {
|
||||
pub kind: ItemKind,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
/// View state saved with a model (not part of its definition): the items the viewport hides.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct View {
|
||||
#[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
|
||||
pub hidden: BTreeSet<Item>,
|
||||
}
|
||||
|
||||
impl View {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.hidden.is_empty()
|
||||
}
|
||||
|
||||
pub fn is_hidden(&self, kind: ItemKind, name: &str) -> bool {
|
||||
self.hidden.contains(&Item { kind, name: name.to_string() })
|
||||
}
|
||||
|
||||
fn check(&self) -> Result<()> {
|
||||
if self.hidden.len() > MAX_HIDDEN {
|
||||
return Err(Error::Limit(format!("a view hides at most {MAX_HIDDEN} items")));
|
||||
}
|
||||
if self.hidden.iter().any(|i| i.name.is_empty() || i.name.len() > MAX_HIDDEN_NAME) {
|
||||
return invalid(format!("{MANIFEST}: a hidden item's name is 1 to {MAX_HIDDEN_NAME} bytes"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// One journal entry: a command id and its parameters.
|
||||
pub type JournalEntry = (String, Value);
|
||||
|
||||
@@ -185,6 +254,7 @@ pub struct ModelFile {
|
||||
pub model: Model,
|
||||
pub geometry: Geometry,
|
||||
pub journal: Vec<JournalEntry>,
|
||||
pub view: View,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
@@ -194,6 +264,8 @@ struct Manifest {
|
||||
generator: String,
|
||||
#[serde(default)]
|
||||
geometry: Geometry,
|
||||
#[serde(default, skip_serializing_if = "View::is_empty")]
|
||||
view: View,
|
||||
parts: BTreeMap<String, Part>,
|
||||
}
|
||||
|
||||
@@ -235,11 +307,12 @@ fn journal_text(journal: &[JournalEntry]) -> Result<Vec<u8>> {
|
||||
}
|
||||
|
||||
/// The bytes of a `.fieldcraft` file holding `model`, built on `geometry` by the commands in
|
||||
/// `journal`. The same arguments always give the same bytes.
|
||||
pub fn write(model: &Model, geometry: &Geometry, journal: &[JournalEntry]) -> Result<Vec<u8>> {
|
||||
/// `journal`, shown with `view`. The same arguments always give the same bytes.
|
||||
pub fn write(model: &Model, geometry: &Geometry, journal: &[JournalEntry], view: &View) -> Result<Vec<u8>> {
|
||||
if geometry.meshes.len() > MAX_MESH_SOURCES {
|
||||
return Err(Error::Limit(format!("a model refers to at most {MAX_MESH_SOURCES} imported meshes")));
|
||||
}
|
||||
view.check()?;
|
||||
let mut model_json = serde_json::to_vec_pretty(&model.without_mesh()).map_err(|e| json_error(MODEL, e))?;
|
||||
model_json.push(b'\n');
|
||||
let mesh = mesh::encode(model)?;
|
||||
@@ -249,6 +322,7 @@ pub fn write(model: &Model, geometry: &Geometry, journal: &[JournalEntry]) -> Re
|
||||
format: FORMAT.into(),
|
||||
generator: format!("FieldCraft {}", env!("CARGO_PKG_VERSION")),
|
||||
geometry: geometry.clone(),
|
||||
view: view.clone(),
|
||||
parts: parts.iter().map(|(name, bytes)| (name.to_string(), Part { bytes: bytes.len() as u64, sha256: sha256_hex(bytes) })).collect(),
|
||||
};
|
||||
let mut manifest_json = serde_json::to_vec_pretty(&manifest).map_err(|e| json_error(MANIFEST, e))?;
|
||||
@@ -323,6 +397,7 @@ pub fn read(bytes: &[u8]) -> Result<ModelFile> {
|
||||
if manifest.geometry.meshes.len() > MAX_MESH_SOURCES {
|
||||
return Err(Error::Limit(format!("a model refers to at most {MAX_MESH_SOURCES} imported meshes")));
|
||||
}
|
||||
manifest.view.check()?;
|
||||
if manifest.parts.len() != 3 {
|
||||
return invalid(format!("`{MANIFEST}` must list exactly the parts {MODEL}, {MESH} and {JOURNAL}"));
|
||||
}
|
||||
@@ -347,7 +422,7 @@ pub fn read(bytes: &[u8]) -> Result<ModelFile> {
|
||||
mesh::decode_into(&mut model, &mesh_bin)?;
|
||||
drop(mesh_bin);
|
||||
let journal = read_journal(&journal_json)?;
|
||||
Ok(ModelFile { model, geometry: manifest.geometry, journal })
|
||||
Ok(ModelFile { model, geometry: manifest.geometry, journal, view: manifest.view })
|
||||
}
|
||||
|
||||
fn read_journal(bytes: &[u8]) -> Result<Vec<JournalEntry>> {
|
||||
|
||||
@@ -23,15 +23,45 @@ use crate::{EXTENSION, Error, MAX_FILE_BYTES, Result};
|
||||
/// The recovery folder of the browser build.
|
||||
pub const BROWSER_DIR: &str = "/recovery";
|
||||
|
||||
/// The recovery folder: `FIELDCRAFT_RECOVERY_DIR`, else `FieldCraft/recovery` (`fieldcraft/` on
|
||||
/// Linux) in the platform's per-user data folder; [`BROWSER_DIR`] in the browser.
|
||||
/// The recovery folder of automated runs (a control channel, CI): a temporary folder, so their
|
||||
/// autosaves never reach the user's own recovery folder.
|
||||
pub fn automation_dir() -> PathBuf {
|
||||
std::env::temp_dir().join("fieldcraft-automation").join("recovery")
|
||||
}
|
||||
|
||||
/// Set by [`use_automation_dir`].
|
||||
static AUTOMATED: std::sync::OnceLock<()> = std::sync::OnceLock::new();
|
||||
|
||||
/// This process is driven by automation (a control channel): [`data_dir`] is the temporary
|
||||
/// `fieldcraft-automation` folder from now on, so unless `FIELDCRAFT_RECOVERY_DIR` names a
|
||||
/// folder, [`default_dir`] is [`automation_dir`].
|
||||
pub fn use_automation_dir() {
|
||||
let _ = AUTOMATED.set(());
|
||||
}
|
||||
|
||||
/// The recovery folder: `FIELDCRAFT_RECOVERY_DIR`, else `recovery` in [`data_dir`];
|
||||
/// [`BROWSER_DIR`] in the browser.
|
||||
pub fn default_dir() -> Option<PathBuf> {
|
||||
if cfg!(target_arch = "wasm32") {
|
||||
return Some(PathBuf::from(BROWSER_DIR));
|
||||
}
|
||||
if let Some(d) = std::env::var_os("FIELDCRAFT_RECOVERY_DIR").filter(|d| !d.is_empty()) {
|
||||
return Some(PathBuf::from(d));
|
||||
}
|
||||
data_dir().map(|d| d.join("recovery"))
|
||||
}
|
||||
|
||||
/// The app's per-user data folder, which holds the recovery, crash and log folders: the
|
||||
/// platform's (`FieldCraft`, `fieldcraft` on Linux), or `fieldcraft-automation` in the temporary
|
||||
/// folder in automated runs ([`use_automation_dir`], or the `CI` environment variable set).
|
||||
/// `None` in the browser and where the platform names no such folder.
|
||||
pub fn data_dir() -> Option<PathBuf> {
|
||||
if cfg!(target_arch = "wasm32") {
|
||||
return None;
|
||||
}
|
||||
let env = |k: &str| std::env::var_os(k).filter(|d| !d.is_empty()).map(PathBuf::from);
|
||||
if let Some(d) = env("FIELDCRAFT_RECOVERY_DIR") {
|
||||
return Some(d);
|
||||
if AUTOMATED.get().is_some() || env("CI").is_some() {
|
||||
return automation_dir().parent().map(Path::to_path_buf);
|
||||
}
|
||||
let (root, name) = if cfg!(windows) {
|
||||
(env("LOCALAPPDATA")?, "FieldCraft")
|
||||
@@ -40,9 +70,12 @@ pub fn default_dir() -> Option<PathBuf> {
|
||||
} else {
|
||||
(env("XDG_DATA_HOME").or_else(|| env("HOME").map(|h| h.join(".local/share")))?, "fieldcraft")
|
||||
};
|
||||
Some(root.join(name).join("recovery"))
|
||||
Some(root.join(name))
|
||||
}
|
||||
|
||||
/// Entries older than this many days are pruned ([`prune`]).
|
||||
pub const MAX_AGE_DAYS: u64 = 14;
|
||||
|
||||
/// What an entry's `<id>.json` holds.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
@@ -80,6 +113,13 @@ fn unix_now() -> u64 {
|
||||
unix_now_ms() / 1000
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
/// Seconds since the autosave (0 without a clock).
|
||||
pub fn age(&self) -> u64 {
|
||||
unix_now().saturating_sub(self.saved_at)
|
||||
}
|
||||
}
|
||||
|
||||
fn valid_id(id: &str) -> bool {
|
||||
!id.is_empty() && id.len() <= 64 && id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
|
||||
}
|
||||
@@ -224,6 +264,22 @@ pub fn orphans(dir: &Path) -> Vec<Entry> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Delete the entries nobody needs any more: those older than [`MAX_AGE_DAYS`] and those whose
|
||||
/// model was saved to its own file after the autosave (the file is newer than the entry).
|
||||
/// Entries held by running apps stay. Returns the ids deleted.
|
||||
pub fn prune(dir: &Path) -> Vec<String> {
|
||||
prune_at(dir, unix_now())
|
||||
}
|
||||
|
||||
fn prune_at(dir: &Path, now: u64) -> Vec<String> {
|
||||
let stale = |e: &Entry| {
|
||||
let old = now.saturating_sub(e.saved_at) > MAX_AGE_DAYS * 86_400;
|
||||
let saved_since = e.path.as_deref().and_then(|p| crate::fs::modified(Path::new(p))).is_some_and(|m| m > e.saved_at);
|
||||
old || saved_since
|
||||
};
|
||||
orphans(dir).into_iter().filter(stale).filter(|e| remove(dir, &e.id).is_ok()).map(|e| e.id).collect()
|
||||
}
|
||||
|
||||
/// An entry's autosaved file bytes and its description.
|
||||
pub fn load(dir: &Path, id: &str) -> Result<(Vec<u8>, Entry)> {
|
||||
if !valid_id(id) {
|
||||
@@ -262,6 +318,7 @@ impl Slot {
|
||||
pub fn new(dir: &Path) -> Result<Slot> {
|
||||
create_dir_all(dir)?;
|
||||
lock::sweep(dir);
|
||||
prune(dir);
|
||||
// Unique within the process too: an app started again in the same second (tests that
|
||||
// "crash" and restart) must not take over the crashed app's entry.
|
||||
static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
@@ -291,6 +348,11 @@ impl Slot {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The autosaved model's file (there once [`Slot::write`] has written it).
|
||||
pub fn file(&self) -> PathBuf {
|
||||
file(&self.dir, &self.id, EXTENSION)
|
||||
}
|
||||
|
||||
/// Drop the autosave (nothing is unsaved any more).
|
||||
pub fn clear(&mut self) {
|
||||
if self.has_entry {
|
||||
@@ -361,6 +423,59 @@ mod tests {
|
||||
let _ = fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// Write a left-behind entry saved at `saved_at` for `path`.
|
||||
fn left_behind(d: &Path, id: &str, path: Option<&Path>, saved_at: u64) {
|
||||
fs::create_dir_all(d).unwrap();
|
||||
let entry = Entry { id: id.into(), path: path.map(|p| p.to_string_lossy().to_string()), saved_at, nodes: 0, elements: 0 };
|
||||
fs::write(file(d, id, "json"), serde_json::to_vec(&entry).unwrap()).unwrap();
|
||||
fs::write(file(d, id, EXTENSION), b"x").unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn old_entries_and_entries_saved_since_are_pruned() {
|
||||
let d = dir("prune");
|
||||
let now = unix_now();
|
||||
let day = 86_400;
|
||||
let model = d.join("model.fieldcraft");
|
||||
fs::create_dir_all(&d).unwrap();
|
||||
fs::write(&model, b"saved").unwrap();
|
||||
let written = crate::fs::modified(&model).unwrap();
|
||||
left_behind(&d, "1-1-1", None, now - (MAX_AGE_DAYS + 1) * day);
|
||||
left_behind(&d, "2-2-2", None, now - (MAX_AGE_DAYS - 1) * day);
|
||||
left_behind(&d, "3-3-3", Some(&model), written - 60);
|
||||
left_behind(&d, "4-4-4", Some(&model), written + 60);
|
||||
left_behind(&d, "5-5-5", Some(&d.join("gone.fieldcraft")), now);
|
||||
let mut pruned = prune_at(&d, now);
|
||||
pruned.sort();
|
||||
assert_eq!(pruned, ["1-1-1", "3-3-3"], "too old, and saved since");
|
||||
let listed = orphans(&d);
|
||||
assert!(listed.windows(2).all(|w| w[0].saved_at >= w[1].saved_at), "newest first");
|
||||
let mut kept: Vec<String> = listed.into_iter().map(|e| e.id).collect();
|
||||
kept.sort();
|
||||
assert_eq!(kept, ["2-2-2", "4-4-4", "5-5-5"]);
|
||||
// A running app's entry stays however old it is.
|
||||
let mut a = Slot::new(&d).unwrap();
|
||||
a.write(b"x", None, 0, 0).unwrap();
|
||||
assert!(!prune_at(&d, now + 365 * day).contains(&a.id().to_string()));
|
||||
// Taking a slot prunes.
|
||||
left_behind(&d, "6-6-6", None, 1);
|
||||
let _b = Slot::new(&d).unwrap();
|
||||
assert!(!file(&d, "6-6-6", "json").exists());
|
||||
let _ = fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automated_runs_use_the_temporary_folder() {
|
||||
// `FIELDCRAFT_RECOVERY_DIR` wins when the test runner sets it.
|
||||
if std::env::var_os("FIELDCRAFT_RECOVERY_DIR").is_some_and(|d| !d.is_empty()) {
|
||||
return;
|
||||
}
|
||||
use_automation_dir();
|
||||
assert_eq!(default_dir(), Some(automation_dir()));
|
||||
assert!(automation_dir().starts_with(std::env::temp_dir()));
|
||||
assert_eq!(data_dir().map(|d| d.join("recovery")), Some(automation_dir()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_ids_and_entries_are_refused() {
|
||||
let d = dir("hostile");
|
||||
|
||||
@@ -12,7 +12,9 @@
|
||||
//! - The result is compared with the root by whole folder names: `/work2/x` is not inside
|
||||
//! `/work`.
|
||||
//! - Read and write access are separate; a root left out grants none of its access. Without
|
||||
//! either root ([`Roots::default`]) nothing is confined.
|
||||
//! either root ([`Roots::default`]) nothing is confined. [`Roots::writes_within`] confines
|
||||
//! writes alone (a crash replay may read the model's geometry wherever it is, and writes
|
||||
//! nothing outside a scratch folder).
|
||||
//!
|
||||
//! A path is checked, then opened: another program that swaps a link in between can still win
|
||||
//! that race, so the roots keep an agent to the files it was given rather than guarding against
|
||||
@@ -41,9 +43,28 @@ impl Access {
|
||||
/// The folders file access is confined to; the default confines nothing.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct Roots {
|
||||
/// `None` while unconfined; otherwise the resolved read and write roots (each `None` when
|
||||
/// that access is not granted).
|
||||
confined: Option<[Option<PathBuf>; 2]>,
|
||||
/// `None` while unconfined; otherwise what each of read and write access is granted.
|
||||
confined: Option<[Grant; 2]>,
|
||||
}
|
||||
|
||||
/// What one kind of access is granted while confined.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
enum Grant {
|
||||
/// Not granted.
|
||||
None,
|
||||
/// Granted anywhere.
|
||||
Anywhere,
|
||||
/// Granted inside this resolved folder.
|
||||
Within(PathBuf),
|
||||
}
|
||||
|
||||
fn resolve_root(p: &Path, access: Access) -> Result<PathBuf> {
|
||||
let shown = p.display();
|
||||
let dir = std::fs::canonicalize(p).map_err(|e| Error::Io(format!("the {} root `{shown}`: {e}", access.name())))?;
|
||||
if !dir.is_dir() {
|
||||
return Err(Error::Io(format!("the {} root `{shown}` is not a folder", access.name())));
|
||||
}
|
||||
Ok(dir)
|
||||
}
|
||||
|
||||
impl Roots {
|
||||
@@ -55,16 +76,15 @@ impl Roots {
|
||||
/// Confine reads to `read` and writes to `write`. A root left out grants none of its access.
|
||||
/// Each root must be an existing folder; it is resolved (links followed) once, here.
|
||||
pub fn new(read: Option<&Path>, write: Option<&Path>) -> Result<Roots> {
|
||||
let resolve = |p: Option<&Path>, access: Access| -> Result<Option<PathBuf>> {
|
||||
let Some(p) = p else { return Ok(None) };
|
||||
let shown = p.display();
|
||||
let dir = std::fs::canonicalize(p).map_err(|e| Error::Io(format!("the {} root `{shown}`: {e}", access.name())))?;
|
||||
if !dir.is_dir() {
|
||||
return Err(Error::Io(format!("the {} root `{shown}` is not a folder", access.name())));
|
||||
}
|
||||
Ok(Some(dir))
|
||||
let grant = |p: Option<&Path>, access: Access| -> Result<Grant> {
|
||||
Ok(p.map(|p| resolve_root(p, access)).transpose()?.map_or(Grant::None, Grant::Within))
|
||||
};
|
||||
Ok(Roots { confined: Some([resolve(read, Access::Read)?, resolve(write, Access::Write)?]) })
|
||||
Ok(Roots { confined: Some([grant(read, Access::Read)?, grant(write, Access::Write)?]) })
|
||||
}
|
||||
|
||||
/// Reads anywhere, writes only inside `write` (an existing folder, resolved here).
|
||||
pub fn writes_within(write: &Path) -> Result<Roots> {
|
||||
Ok(Roots { confined: Some([Grant::Anywhere, Grant::Within(resolve_root(write, Access::Write)?)]) })
|
||||
}
|
||||
|
||||
/// Whether any access is confined.
|
||||
@@ -72,10 +92,12 @@ impl Roots {
|
||||
self.confined.is_some()
|
||||
}
|
||||
|
||||
/// The root of `access`, when confined and granted.
|
||||
/// The root of `access`, when confined to one.
|
||||
pub fn root(&self, access: Access) -> Option<&Path> {
|
||||
let roots = self.confined.as_ref()?;
|
||||
roots.get(access as usize).and_then(|r| r.as_deref())
|
||||
match self.confined.as_ref()?.get(access as usize)? {
|
||||
Grant::Within(root) => Some(root),
|
||||
Grant::None | Grant::Anywhere => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The path to use for `access` to `path`: unchanged while unconfined, else the resolved path
|
||||
@@ -84,8 +106,12 @@ impl Roots {
|
||||
pub fn check(&self, path: &Path, access: Access) -> Result<PathBuf> {
|
||||
let Some(roots) = &self.confined else { return Ok(path.to_path_buf()) };
|
||||
let shown = path.display();
|
||||
let Some(root) = roots.get(access as usize).and_then(|r| r.as_deref()) else {
|
||||
return Err(Error::Refused(format!("automation filesystem access is not granted: {} authority is absent: {shown}", access.name())));
|
||||
let root = match roots.get(access as usize) {
|
||||
Some(Grant::Anywhere) => return Ok(path.to_path_buf()),
|
||||
Some(Grant::Within(root)) => root,
|
||||
Some(Grant::None) | None => {
|
||||
return Err(Error::Refused(format!("automation filesystem access is not granted: {} authority is absent: {shown}", access.name())));
|
||||
}
|
||||
};
|
||||
let resolved = resolve(path).map_err(|why| Error::Refused(format!("automation path rejected: {why}: {shown}")))?;
|
||||
if !resolved.starts_with(root) {
|
||||
@@ -209,6 +235,18 @@ mod tests {
|
||||
assert!(Roots::new(None, Some(&d.0.join("file"))).is_err(), "a root is a folder");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writes_within_reads_anywhere() {
|
||||
let d = Dir::new("writes");
|
||||
let r = Roots::writes_within(&d.0).unwrap();
|
||||
assert!(r.is_confined());
|
||||
assert_eq!(r.check(Path::new("/etc/passwd"), Access::Read).unwrap(), Path::new("/etc/passwd"));
|
||||
assert!(r.check(Path::new("/etc/passwd"), Access::Write).is_err());
|
||||
assert_eq!(r.check(&d.0.join("x.inp"), Access::Write).unwrap(), d.0.join("x.inp"));
|
||||
assert_eq!(r.root(Access::Write), Some(d.0.as_path()));
|
||||
assert_eq!(r.root(Access::Read), None);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn links_are_followed() {
|
||||
|
||||