mirror of
https://github.com/bherbruck/solidcraft.git
synced 2026-11-03 10:35:58 +00:00
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 133569e695 |
@@ -1,5 +1,6 @@
|
||||
# cargo-nextest settings for CI (`cargo xtask test` does not use nextest).
|
||||
# CI builds the tests once and runs them in one job on a 32 vCPU runner (.github/workflows/ci.yml).
|
||||
# CI builds the tests once and runs them in shards: 2 for a pull request, 4 for main and the nightly
|
||||
# (.github/workflows/ci.yml).
|
||||
|
||||
[profile.ci]
|
||||
# Heavy tests (one to twelve minutes each on a CI runner) that pull requests skip. They run on
|
||||
@@ -33,14 +34,12 @@ slow-timeout = { period = "60s" }
|
||||
[profile.ci.junit]
|
||||
path = "junit.xml"
|
||||
|
||||
# The action matrix sample runs its designs in parallel workers (ACTION_MATRIX_JOBS, set to match in
|
||||
# ci.yml). Its workers reserve that many of nextest's threads, so the cores are not oversubscribed
|
||||
# (a pi-case hole that takes 8 s alone went past the matrix's 90 s action limit when they were),
|
||||
# and it starts first, beside the other slow tests.
|
||||
# The action matrix sample runs its designs in parallel worker processes, one per CPU. Run with
|
||||
# other tests beside it (the heavy ones on main), a pi-case hole that takes 8 s alone (#952 makes
|
||||
# it a real hole) went past the matrix's 90 s action limit. It runs on its own.
|
||||
[[profile.ci.overrides]]
|
||||
filter = "binary(action_matrix) & test(=action_matrix_sample)"
|
||||
threads-required = 12
|
||||
priority = 100
|
||||
threads-required = "num-cpus"
|
||||
|
||||
|
||||
# The slowest tests start first, so a shard does not end with one of them running alone on a
|
||||
|
||||
@@ -7,5 +7,4 @@ self-hosted-runner:
|
||||
- blacksmith-4vcpu-ubuntu-2404
|
||||
- blacksmith-8vcpu-ubuntu-2404
|
||||
- blacksmith-16vcpu-ubuntu-2404
|
||||
- blacksmith-32vcpu-ubuntu-2404
|
||||
- blacksmith-8vcpu-windows-2025
|
||||
|
||||
+46
-115
@@ -8,13 +8,12 @@
|
||||
# whole workspace, as do pushes to main that change code, the nightly run and Run workflow.
|
||||
# Documentation, packaging, the other workflows and the GitHub bots' scripts select nothing:
|
||||
# no native job runs for them, on pull requests or on main.
|
||||
# Tests are built and run in one job on a big runner, slowest first, starting beside the repository
|
||||
# checks (no archive to upload and download). A few heavy tests (see .config/nextest.toml) are
|
||||
# Tests are built once and run in shards. A few heavy tests (see .config/nextest.toml) are
|
||||
# skipped on pull requests and run on pushes to main and nightly. The Windows jobs (D3D12 shaders
|
||||
# and app startup), the reference tests and the doc tests run on main and nightly only, not on
|
||||
# pull requests (the fast lane, in Select checks); a break there is fixed forward on main. Only
|
||||
# main saves the build caches; pull requests restore them. sccache is on a Blacksmith sticky disk that
|
||||
# only main commits.
|
||||
# main saves the build caches; pull requests restore them. On pull requests the test build and the
|
||||
# shards start only after the format and repository checks pass.
|
||||
# A push to main runs only the repository checks when a passing merge-queue run tested that very
|
||||
# commit, or when nothing a build reads changed since the last push to main whose run passed.
|
||||
# Otherwise it runs everything.
|
||||
@@ -30,13 +29,14 @@
|
||||
# reads `ci` from the newest run of a commit, so a run without it would block a PR that passed.
|
||||
# Cross-compilation is opt-in through Run workflow; release builds remain in release.yml.
|
||||
# Every Linux job runs on Blacksmith's Ubuntu 24.04 runners (blacksmith-<N>vcpu-ubuntu-2404), sized
|
||||
# per job: 32 vCPU for the tests, 16 for Clippy, the archive build (nightly) and the merge queue's, 8 for compiles, doc and reference tests, 4 for the light checks, 2 for Select checks and ci.
|
||||
# per job: 16 vCPU for Build tests, Clippy and the merge queue's test shards, 8 for compiles, the
|
||||
# other test shards, doc and reference tests, 4 for the light checks, 2 for Select checks and ci.
|
||||
# The Windows shader job runs on Blacksmith's Windows Server 2025 runners (blacksmith-8vcpu-windows-2025);
|
||||
# the Windows app startup smoke stays on windows-latest, which has a desktop session that presents frames.
|
||||
# Pull requests, forks included, the merge queue, pushes to main and the nightly run all use them:
|
||||
# the runners are ephemeral, fork runs get no secrets, and main saves the build caches that every
|
||||
# other run restores read-only. Nightly and by hand, Build tests also makes an archive the matrix
|
||||
# jobs run; Blacksmith's image matches ubuntu-24.04, so the archive and the recorded goldens behave the
|
||||
# other run restores read-only. The tests are built once (Build tests) into an archive the shards
|
||||
# run; Blacksmith's image matches ubuntu-24.04, so the archive and the recorded goldens behave the
|
||||
# same.
|
||||
name: CI
|
||||
|
||||
@@ -178,12 +178,9 @@ jobs:
|
||||
git diff --no-renames --name-only -z "$BASE_SHA...$HEAD_SHA" > "$RUNNER_TEMP/ci-paths"
|
||||
while IFS= read -r -d '' path; do
|
||||
case "$path" in crates/kernel/*|vendor/truck-*) kernel=true ;; esac
|
||||
# What a pull request re-checks the goldens for: the kernel, truck and the goldens
|
||||
# themselves (a re-record is checked before it is queued). The goldens are frozen, so
|
||||
# on any other change they would only re-check unchanged results; the merge queue,
|
||||
# main and the nightly run every seed before anything lands.
|
||||
# What can change a robustness golden: the kernel and the crates a design is built with.
|
||||
case "$path" in
|
||||
crates/kernel/*|vendor/truck-*|tests/robustness/*) goldens=true ;;
|
||||
crates/kernel/*|crates/engine/*|crates/doc/*|crates/sketch/*|crates/geom/*|vendor/truck-*|tests/robustness/*) goldens=true ;;
|
||||
esac
|
||||
# What the Windows D3D12 jobs exercise: the GPU crate and its shaders, the app and
|
||||
# its startup, the viewport's wgpu glue, the vendored egui-wgpu, their scripts.
|
||||
@@ -340,33 +337,25 @@ jobs:
|
||||
|
||||
build-tests:
|
||||
name: Build tests
|
||||
# The archive is for the action matrix and the property tests, which run only nightly and by
|
||||
# hand. Pull requests, the merge queue and main build and run their tests in the `tests` job.
|
||||
needs: changes
|
||||
if: ${{ !cancelled() && needs.changes.result == 'success' && needs.changes.outputs.native == 'true' && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') }}
|
||||
# Fail fast on pull requests: the test archive (and so the shards) waits for the repository
|
||||
# checks, the most common cheap failure; heavy jobs used to run on to the end beside a failed
|
||||
# format check. Main, nightly and Run workflow build regardless, so the action matrix and the
|
||||
# property tests that hang off this job keep their signal.
|
||||
needs: [changes, checks]
|
||||
if: ${{ !cancelled() && needs.changes.result == 'success' && needs.changes.outputs.native == 'true' && (github.event_name != 'pull_request' || needs.checks.result == 'success') }}
|
||||
runs-on: blacksmith-16vcpu-ubuntu-2404
|
||||
# Fork builds start from main's cache, read-only; give them room to finish and upload.
|
||||
timeout-minutes: ${{ (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository) && 60 || 45 }}
|
||||
env:
|
||||
CARGO_INCREMENTAL: "0"
|
||||
RUSTC_WRAPPER: sccache
|
||||
SCCACHE_DIR: /home/runner/.cache/sccache
|
||||
SCCACHE_CACHE_SIZE: 20G
|
||||
SCCACHE_GHA_ENABLED: "true"
|
||||
SCCACHE_IGNORE_SERVER_IO_ERROR: "1"
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Size parallel compiles to the job's memory
|
||||
run: scripts/ci/build-jobs.sh
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
# sccache lives on a Blacksmith sticky disk (an ext4 volume cloned from the last snapshot,
|
||||
# no 10 GB limit and no download). Only main commits it; pull requests, the merge queue and
|
||||
# forks mount a clone and never write back, so nothing they build can reach main's cache.
|
||||
- name: Mount the compiler cache
|
||||
uses: useblacksmith/stickydisk@3f6be1451e3cad893b778bc93495c80452a5da26 # v1.7.2
|
||||
continue-on-error: true
|
||||
with:
|
||||
key: ${{ github.repository }}-sccache-archive
|
||||
path: /home/runner/.cache/sccache
|
||||
commit: ${{ github.ref == 'refs/heads/main' && 'on-change' || 'false' }}
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
|
||||
with:
|
||||
key: native-tests
|
||||
@@ -398,94 +387,63 @@ jobs:
|
||||
run: sccache --show-stats
|
||||
|
||||
tests:
|
||||
name: Native Linux tests
|
||||
needs: changes
|
||||
if: ${{ !cancelled() && needs.changes.result == 'success' && needs.changes.outputs.native == 'true' }}
|
||||
# Builds the tests and runs them in one job on a big runner: there is no archive to upload
|
||||
# and download (3 GB on a full run), and the job starts beside the repository checks, not
|
||||
# after them. nextest hands tests to its threads as they free up, the slowest first (priority
|
||||
# in .config/nextest.toml), so they start at once and no core idles at the end.
|
||||
runs-on: blacksmith-32vcpu-ubuntu-2404
|
||||
name: Native Linux tests (${{ matrix.shard }}/4)
|
||||
needs: [changes, checks, build-tests]
|
||||
if: ${{ !cancelled() && needs.changes.outputs.native == 'true' && (github.event_name != 'pull_request' || needs.checks.result == 'success') && needs.build-tests.result == 'success' }}
|
||||
runs-on: ${{ github.event_name == 'merge_group' && 'blacksmith-16vcpu-ubuntu-2404' || 'blacksmith-8vcpu-ubuntu-2404' }}
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
# Pull requests test their affected crates in 2 shards; main and the nightly use 4.
|
||||
shard: ${{ fromJSON(github.event_name == 'pull_request' && '[1, 2]' || '[1, 2, 3, 4]') }}
|
||||
env:
|
||||
# Pictures (snapshots, screenshots, ui.render, the viewport's offscreen tests) are drawn on
|
||||
# the GPU. The runner has none: Mesa's lavapipe (software Vulkan) draws them, and a test that
|
||||
# would skip for want of an adapter fails instead.
|
||||
SOLIDCRAFT_GPU: software
|
||||
SOLIDCRAFT_REQUIRE_GPU: "1"
|
||||
ACTION_MATRIX_JOBS: "12"
|
||||
CARGO_INCREMENTAL: "0"
|
||||
RUSTC_WRAPPER: sccache
|
||||
SCCACHE_DIR: /home/runner/.cache/sccache
|
||||
SCCACHE_CACHE_SIZE: 20G
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Install a software Vulkan driver (lavapipe)
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends mesa-vulkan-drivers libvulkan1
|
||||
- name: Size parallel compiles to the job's memory
|
||||
run: scripts/ci/build-jobs.sh
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
# sccache lives on a Blacksmith sticky disk (an ext4 volume cloned from the last snapshot,
|
||||
# no 10 GB limit and no download). Only main commits it; pull requests, the merge queue and
|
||||
# forks mount a clone and never write back, so nothing they build can reach main's cache.
|
||||
- name: Mount the compiler cache
|
||||
uses: useblacksmith/stickydisk@3f6be1451e3cad893b778bc93495c80452a5da26 # v1.7.2
|
||||
continue-on-error: true
|
||||
with:
|
||||
key: ${{ github.repository }}-sccache-tests
|
||||
path: /home/runner/.cache/sccache
|
||||
commit: ${{ github.ref == 'refs/heads/main' && 'on-change' || 'false' }}
|
||||
# Main saves the cache; every other run restores it, read-only.
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
|
||||
with:
|
||||
key: native-tests
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
- name: Set up compiler cache
|
||||
uses: mozilla-actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11
|
||||
with:
|
||||
version: v0.16.0
|
||||
- uses: taiki-e/install-action@1168f6810a3cb30a3514bf5756a3b7f0422c6df8 # v2.87.28
|
||||
with:
|
||||
tool: cargo-nextest
|
||||
# Each shard runs the archive the Build tests job made.
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
name: nextest-archive
|
||||
- name: Run tests
|
||||
env:
|
||||
EVENT_NAME: ${{ github.event_name }}
|
||||
GOLDENS: ${{ needs.changes.outputs.goldens }}
|
||||
FULL: ${{ needs.changes.outputs.full }}
|
||||
PACKAGES: ${{ needs.changes.outputs.packages }}
|
||||
SHARD: ${{ matrix.shard }}
|
||||
SHARDS: ${{ github.event_name == 'pull_request' && 2 || 4 }}
|
||||
# The robustness golden seeds a pull request skips: each takes one to twenty minutes under
|
||||
# CI load, together about four fifths of the goldens' time. Pushes to main, the merge
|
||||
# queue and the nightly run every seed.
|
||||
SLOW_SEEDS: 81|45|20|24|95|02|57|40|18|48|32|46|85|61|77|34|14
|
||||
run: |
|
||||
# Pull requests skip the heavy tests (default-filter in .config/nextest.toml); `default()`
|
||||
# below is that filter, so a pull request still runs only what it ran before.
|
||||
base='default()'
|
||||
if [ "$EVENT_NAME" = pull_request ]; then
|
||||
# The action matrix sample (about 6 minutes on all cores) runs in the merge queue, on
|
||||
# main and nightly, not on every pull request push.
|
||||
base='default() & not (binary(action_matrix) & test(=action_matrix_sample))'
|
||||
fi
|
||||
# Pull requests skip the heavy tests (default-filter in .config/nextest.toml).
|
||||
filter=()
|
||||
if [ "$EVENT_NAME" != pull_request ]; then
|
||||
# The boolean property tests draw new random inputs every run; they run only in the
|
||||
# nightly property-tests job, so a known kernel bug cannot turn main red at random.
|
||||
base='not (package(solidcraft-kernel) & binary(boolean_props))'
|
||||
filter=(--ignore-default-filter -E 'not (package(solidcraft-kernel) & binary(boolean_props))')
|
||||
elif [ "$GOLDENS" = true ]; then
|
||||
# A pull request that can change a robustness golden (tests/robustness/goldens.json)
|
||||
# also checks every seed but the slow ones, in the same run so they share its cores.
|
||||
base="(default() & not (binary(action_matrix) & test(=action_matrix_sample))) | (package(solidcraft-engine) & test(/^tests::robustness_goldens::/) & not test(/^tests::robustness_goldens::seed_($SLOW_SEEDS)\$/))"
|
||||
filter=(--ignore-default-filter -E "default() | (package(solidcraft-engine) & test(/^tests::robustness_goldens::/) & not test(/^tests::robustness_goldens::seed_($SLOW_SEEDS)\$/))")
|
||||
fi
|
||||
junit=${CARGO_TARGET_DIR:-target}/nextest/ci/junit.xml
|
||||
rm -f "$junit"
|
||||
# Pull requests test the affected packages (scripts/ci/affected.py).
|
||||
scope=(--workspace)
|
||||
if [ "$FULL" != true ]; then scope=(); for p in $PACKAGES; do scope+=(-p "$p"); done; fi
|
||||
status=0
|
||||
cargo nextest run "${scope[@]}" --cargo-profile ci --locked --profile ci --no-tests=pass \
|
||||
--ignore-default-filter -E "$base" || status=1
|
||||
if [ "$status" != 0 ]; then
|
||||
# Extract into ./target: tests that run a built binary (env!("CARGO_BIN_EXE_*")) have
|
||||
# the build job's path, which is the same checkout path here.
|
||||
run=(cargo nextest run --archive-file tests.tar.zst --workspace-remap . --extract-to . --extract-overwrite)
|
||||
if ! "${run[@]}" --profile ci --partition "slice:$SHARD/$SHARDS" --no-tests=pass "${filter[@]}"; then
|
||||
# A failed golden gets the hint to re-record it (junit.xml lists the failures).
|
||||
if [ -f "$junit" ] && tr '\n' ' ' < "$junit" | grep -q '<testcase name="tests::robustness_goldens::[^"]*"[^>]*>[[:space:]]*<failure'; then
|
||||
echo "::error::A robustness golden changed. If the new result is intended, re-record it in this pull request and say why:"
|
||||
@@ -493,14 +451,11 @@ jobs:
|
||||
fi
|
||||
exit 1
|
||||
fi
|
||||
- name: Compiler cache statistics
|
||||
if: always()
|
||||
run: sccache --show-stats
|
||||
- name: Upload test timings
|
||||
if: always()
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: junit
|
||||
name: junit-${{ matrix.shard }}
|
||||
path: ${{ env.CARGO_TARGET_DIR || 'target' }}/nextest/ci/junit.xml
|
||||
retention-days: 7
|
||||
|
||||
@@ -605,23 +560,13 @@ jobs:
|
||||
env:
|
||||
CARGO_INCREMENTAL: "0"
|
||||
RUSTC_WRAPPER: sccache
|
||||
SCCACHE_DIR: /home/runner/.cache/sccache
|
||||
SCCACHE_CACHE_SIZE: 20G
|
||||
SCCACHE_GHA_ENABLED: "true"
|
||||
SCCACHE_IGNORE_SERVER_IO_ERROR: "1"
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Size parallel compiles to the job's memory
|
||||
run: scripts/ci/build-jobs.sh
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
# sccache lives on a Blacksmith sticky disk (an ext4 volume cloned from the last snapshot,
|
||||
# no 10 GB limit and no download). Only main commits it; pull requests, the merge queue and
|
||||
# forks mount a clone and never write back, so nothing they build can reach main's cache.
|
||||
- name: Mount the compiler cache
|
||||
uses: useblacksmith/stickydisk@3f6be1451e3cad893b778bc93495c80452a5da26 # v1.7.2
|
||||
continue-on-error: true
|
||||
with:
|
||||
key: ${{ github.repository }}-sccache-doc
|
||||
path: /home/runner/.cache/sccache
|
||||
commit: ${{ github.ref == 'refs/heads/main' && 'on-change' || 'false' }}
|
||||
# Main saves the cache; every other run restores it, read-only.
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
|
||||
with:
|
||||
@@ -663,23 +608,13 @@ jobs:
|
||||
env:
|
||||
CARGO_INCREMENTAL: "0"
|
||||
RUSTC_WRAPPER: sccache
|
||||
SCCACHE_DIR: /home/runner/.cache/sccache
|
||||
SCCACHE_CACHE_SIZE: 20G
|
||||
SCCACHE_GHA_ENABLED: "true"
|
||||
SCCACHE_IGNORE_SERVER_IO_ERROR: "1"
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Size parallel compiles to the job's memory
|
||||
run: scripts/ci/build-jobs.sh
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
# sccache lives on a Blacksmith sticky disk (an ext4 volume cloned from the last snapshot,
|
||||
# no 10 GB limit and no download). Only main commits it; pull requests, the merge queue and
|
||||
# forks mount a clone and never write back, so nothing they build can reach main's cache.
|
||||
- name: Mount the compiler cache
|
||||
uses: useblacksmith/stickydisk@3f6be1451e3cad893b778bc93495c80452a5da26 # v1.7.2
|
||||
continue-on-error: true
|
||||
with:
|
||||
key: ${{ github.repository }}-sccache-oracle
|
||||
path: /home/runner/.cache/sccache
|
||||
commit: ${{ github.ref == 'refs/heads/main' && 'on-change' || 'false' }}
|
||||
# Main saves the cache; every other run restores it, read-only.
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
|
||||
with:
|
||||
@@ -811,7 +746,6 @@ jobs:
|
||||
DOCTESTS: ${{ needs.changes.outputs.doctests }}
|
||||
CLIPPY: ${{ needs.clippy.result }}
|
||||
BUILD: ${{ needs.build-tests.result }}
|
||||
EVENT_NAME: ${{ github.event_name }}
|
||||
TESTS: ${{ needs.tests.result }}
|
||||
DOCS: ${{ needs.doc-tests.result }}
|
||||
ORACLE: ${{ needs.oracle.result }}
|
||||
@@ -826,10 +760,7 @@ jobs:
|
||||
fi
|
||||
if [ "$NATIVE" = true ]; then
|
||||
test "$CLIPPY" = success
|
||||
# The archive for the action matrix and property tests exists nightly and by hand only.
|
||||
if [ "$EVENT_NAME" = schedule ] || [ "$EVENT_NAME" = workflow_dispatch ]; then
|
||||
test "$BUILD" = success
|
||||
fi
|
||||
test "$BUILD" = success
|
||||
test "$TESTS" = success
|
||||
fi
|
||||
if [ "$DOCTESTS" = true ]; then
|
||||
|
||||
+1
-24
@@ -57,23 +57,6 @@ Editable drawing code, native projects and shipped exports are collected under `
|
||||
| docs/book/src/generated/tool-preview.png | SolidCraft contributors | rendered by `cargo xtask book` (`solidcraft-cli snapshot docs/book/scripts/tool-preview.json`; gitignored) | MIT OR Apache-2.0 |
|
||||
| assets/fonts/liberation-sans/LiberationSans-Regular.ttf | Red Hat, Inc. (Liberation Fonts 2.x; digitized data Google) | https://github.com/liberationfonts (Debian fonts-liberation), unmodified; licence text in assets/fonts/liberation-sans/OFL.txt; used for sketch Text outlines | SIL OFL 1.1 |
|
||||
| assets/fonts/biz-udp-gothic/BIZUDPGothic-Regular.ttf | The BIZ UDGothic Project Authors | https://github.com/googlefonts/morisawa-biz-ud-gothic (Google Fonts), unmodified; licence text in assets/fonts/biz-udp-gothic/OFL.txt; used for web UI Japanese font | SIL OFL 1.1 |
|
||||
| tests/step-conformance/cone_point.step | step-conformance contributors | generated from formulas by https://github.com/dan335/step-conformance (corpus/generated, 96f30bb); import regression fixture | CC0-1.0 |
|
||||
| tests/step-conformance/cone_point_vertex.step | step-conformance contributors | generated from formulas by https://github.com/dan335/step-conformance (corpus/generated, 96f30bb); import regression fixture | CC0-1.0 |
|
||||
| tests/step-conformance/cylinder.step | step-conformance contributors | generated from formulas by https://github.com/dan335/step-conformance (corpus/generated, 96f30bb); import regression fixture | CC0-1.0 |
|
||||
| tests/step-conformance/cylinder_inch.step | step-conformance contributors | generated from formulas by https://github.com/dan335/step-conformance (corpus/generated, 96f30bb); import regression fixture | CC0-1.0 |
|
||||
| tests/step-conformance/cylinder_nurbs.step | step-conformance contributors | generated from formulas by https://github.com/dan335/step-conformance (corpus/generated, 96f30bb); import regression fixture | CC0-1.0 |
|
||||
| tests/step-conformance/cylinder_placed.step | step-conformance contributors | generated from formulas by https://github.com/dan335/step-conformance (corpus/generated, 96f30bb); import regression fixture | CC0-1.0 |
|
||||
| tests/step-conformance/cylinder_seam.step | step-conformance contributors | generated from formulas by https://github.com/dan335/step-conformance (corpus/generated, 96f30bb); import regression fixture | CC0-1.0 |
|
||||
| tests/step-conformance/cylinder_twice.step | step-conformance contributors | generated from formulas by https://github.com/dan335/step-conformance (corpus/generated, 96f30bb); import regression fixture | CC0-1.0 |
|
||||
| tests/step-conformance/dome.step | step-conformance contributors | generated from formulas by https://github.com/dan335/step-conformance (corpus/generated, 96f30bb); import regression fixture | CC0-1.0 |
|
||||
| tests/step-conformance/dome_nurbs.step | step-conformance contributors | generated from formulas by https://github.com/dan335/step-conformance (corpus/generated, 96f30bb); import regression fixture | CC0-1.0 |
|
||||
| tests/step-conformance/far_cylinder.step | step-conformance contributors | generated from formulas by https://github.com/dan335/step-conformance (corpus/generated, 96f30bb); import regression fixture | CC0-1.0 |
|
||||
| tests/step-conformance/grooved_shaft.step | step-conformance contributors | generated from formulas by https://github.com/dan335/step-conformance (corpus/generated, 96f30bb); import regression fixture | CC0-1.0 |
|
||||
| tests/step-conformance/plate_100_holes.step | step-conformance contributors | generated from formulas by https://github.com/dan335/step-conformance (corpus/generated, 96f30bb); import regression fixture | CC0-1.0 |
|
||||
| tests/step-conformance/sheet_disc.step | step-conformance contributors | generated from formulas by https://github.com/dan335/step-conformance (corpus/generated, 96f30bb); import regression fixture | CC0-1.0 |
|
||||
| tests/step-conformance/tiny_pin.step | step-conformance contributors | generated from formulas by https://github.com/dan335/step-conformance (corpus/generated, 96f30bb); import regression fixture | CC0-1.0 |
|
||||
| tests/step-conformance/torus_ring_nurbs.step | step-conformance contributors | generated from formulas by https://github.com/dan335/step-conformance (corpus/generated, 96f30bb); import regression fixture | CC0-1.0 |
|
||||
| tests/step-conformance/washer.step | step-conformance contributors | generated from formulas by https://github.com/dan335/step-conformance (corpus/generated, 96f30bb); import regression fixture | CC0-1.0 |
|
||||
| tests/oracle/17-loft/reference.stl | SolidCraft contributors | triangulation of our own recipe (tests/oracle/17-loft/recipe.json) built with FreeCAD as an external tool by tools/freecad-oracle | MIT OR Apache-2.0 |
|
||||
| tests/oracle/23-bracket-multifeature/reference.stl | SolidCraft contributors | triangulation of our own recipe (tests/oracle/23-bracket-multifeature/recipe.json) built with FreeCAD as an external tool by tools/freecad-oracle | MIT OR Apache-2.0 |
|
||||
| tests/oracle/28-blind-pocket-fillets/reference.stl | SolidCraft contributors | triangulation of our own recipe (tests/oracle/28-blind-pocket-fillets/recipe.json) built with FreeCAD as an external tool by tools/freecad-oracle | MIT OR Apache-2.0 |
|
||||
@@ -94,6 +77,7 @@ Editable drawing code, native projects and shipped exports are collected under `
|
||||
| tests/oracle/61-shaft-keyway/reference.stl | SolidCraft contributors | triangulation of our own recipe (tests/oracle/61-shaft-keyway/recipe.json) built with FreeCAD as an external tool by tools/freecad-oracle | MIT OR Apache-2.0 |
|
||||
| tests/oracle/63-hinge-knuckle/reference.stl | SolidCraft contributors | triangulation of our own recipe (tests/oracle/63-hinge-knuckle/recipe.json) built with FreeCAD as an external tool by tools/freecad-oracle | MIT OR Apache-2.0 |
|
||||
| tests/oracle/65-sketch-gear-tooth/reference.stl | SolidCraft contributors | triangulation of our own recipe (tests/oracle/65-sketch-gear-tooth/recipe.json) built with FreeCAD as an external tool by tools/freecad-oracle | MIT OR Apache-2.0 |
|
||||
|
||||
| assets/appearances/library.rs | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 |
|
||||
| assets/fonts/biz-udp-gothic/OFL.txt | The BIZ UDGothic Project Authors | Unmodified accompanying font licence | SIL OFL 1.1 |
|
||||
| assets/fonts/ibm-plex-mono/OFL.txt | IBM Corp. | Unmodified accompanying font licence | SIL OFL 1.1 |
|
||||
@@ -118,28 +102,21 @@ Editable drawing code, native projects and shipped exports are collected under `
|
||||
| assets/locales/cs.json | potuzai | Czech translation of the English catalog, contributed upstream | MIT OR Apache-2.0 |
|
||||
| assets/locales/da.json | SolidCraft contributors | Original Danish translation of SolidCraft's English catalog; no commercial CAD text used | MIT OR Apache-2.0 |
|
||||
| assets/locales/de.json | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 |
|
||||
| assets/locales/en-GB.json | SolidCraft contributors | English (UK): the English catalog's messages whose spelling differs, in UK spelling | MIT OR Apache-2.0 |
|
||||
| assets/locales/en.json | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 |
|
||||
| assets/locales/es.json | jawler | Spanish (Spain) translation of the English catalog, contributed upstream | MIT OR Apache-2.0 |
|
||||
| assets/locales/fr.json | rlartot | French translation of the English catalog, contributed upstream | MIT OR Apache-2.0 |
|
||||
| assets/locales/gl.json | Pablo López (pablopeza) | Galician translation of the English catalog, contributed upstream | MIT OR Apache-2.0 |
|
||||
| assets/locales/hu.json | SolidCraft contributors | Original Hungarian translation of SolidCraft's English catalog; no commercial CAD text used | MIT OR Apache-2.0 |
|
||||
| assets/locales/id.json | SolidCraft contributors | Original Indonesian translation of SolidCraft's English catalog; no commercial CAD text used | MIT OR Apache-2.0 |
|
||||
| assets/locales/it.json | SolidCraft contributors | Original Italian translation of SolidCraft's English catalog; no commercial CAD text used | MIT OR Apache-2.0 |
|
||||
| assets/locales/ja.json | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 |
|
||||
| assets/locales/ko.json | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 |
|
||||
| assets/locales/ms.json | A.Hakim (a-hakim) | Malay translation of the English message catalog | MIT OR Apache-2.0 |
|
||||
| assets/locales/nl.json | SolidCraft contributors | Original Dutch translation of SolidCraft's English catalog; no commercial CAD text used | MIT OR Apache-2.0 |
|
||||
| assets/locales/pl.json | cyryllo | Polish translation of the English catalog, contributed upstream | MIT OR Apache-2.0 |
|
||||
| assets/locales/ru.json | Alex Pro (del000) | Russian translation of the English catalog, contributed upstream | MIT OR Apache-2.0 |
|
||||
| assets/locales/sv.json | SolidCraft contributors | Original Swedish translation of SolidCraft's English catalog; no commercial CAD text used | MIT OR Apache-2.0 |
|
||||
| assets/locales/pt-BR.json | DuBearte | Brazilian Portuguese translation of the English catalog, contributed upstream | MIT OR Apache-2.0 |
|
||||
| assets/locales/ro.json | SolidCraft contributors | Original Romanian translation of SolidCraft's English catalog; no commercial CAD text used | MIT OR Apache-2.0 |
|
||||
| assets/locales/tr.json | macrulz54 | Turkish translation of the English catalog, contributed upstream | MIT OR Apache-2.0 |
|
||||
| assets/locales/uk.json | Igor Bronovskyi (BrunIF) | Ukrainian translation of the English catalog, contributed upstream | MIT OR Apache-2.0 |
|
||||
| assets/locales/vi.json | vandang890615 | Vietnamese translation of the English catalog, contributed upstream | MIT OR Apache-2.0 |
|
||||
| assets/locales/zh.json | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 |
|
||||
| assets/locales/zh-TW.json | SolidCraft contributors | Original Traditional Chinese (Taiwan) translation of SolidCraft's English catalog; no commercial CAD text used | MIT OR Apache-2.0 |
|
||||
| assets/materials/library.rs | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 |
|
||||
| assets/platforms/linux/ai.storyteller.solidcraft.desktop | PhotoCraft / SolidCraft contributors | PhotoCraft packaging templates (https://github.com/storytold/photocraft), adapted for SolidCraft | Apache-2.0 |
|
||||
| assets/platforms/linux/ai.storyteller.solidcraft.metainfo.xml.in | PhotoCraft / SolidCraft contributors | PhotoCraft packaging templates (https://github.com/storytold/photocraft), adapted for SolidCraft | Apache-2.0 |
|
||||
|
||||
+1
-1
@@ -199,7 +199,7 @@ Check that validation after merging. They are listed in
|
||||
`.config/nextest.toml` and the [testing page](docs/book/src/dev/testing.md):
|
||||
|
||||
- `solidcraft-engine`: `tests::hostile_params_never_panic`, everything in `tests::robustness` and
|
||||
the seeds of `tests::robustness_goldens` (`seed_00` … `seed_95`; pull requests that change the kernel, truck or the goldens run all but the slowest, `SLOW_SEEDS` in `ci.yml`),
|
||||
the seeds of `tests::robustness_goldens` (`seed_00` … `seed_95`; pull requests matching the workflow's geometry paths run all but the slowest, `SLOW_SEEDS` in `ci.yml`),
|
||||
`pattern_suppress_tests::enclosure_arc_extinction_keeps_a_real_sharp_inner_lip_after_resize_and_reopen`,
|
||||
`pattern_suppress_tests::enclosure_datums_follow_wall_height_and_board_depth_with_material_proofs`,
|
||||
`cmd::plastic::tests::enclosure_snap_fit_follows_resized_front_wall`, the `atomic_commands` contract tests
|
||||
|
||||
Generated
+17
-17
@@ -4162,7 +4162,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft"
|
||||
version = "0.18.2"
|
||||
version = "0.18.0"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"eframe",
|
||||
@@ -4193,11 +4193,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-3dx-client"
|
||||
version = "0.18.2"
|
||||
version = "0.18.0"
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-cli"
|
||||
version = "0.18.2"
|
||||
version = "0.18.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"serde_json",
|
||||
@@ -4208,7 +4208,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-derive"
|
||||
version = "0.18.2"
|
||||
version = "0.18.0"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -4217,7 +4217,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-doc"
|
||||
version = "0.18.2"
|
||||
version = "0.18.0"
|
||||
dependencies = [
|
||||
"log",
|
||||
"serde",
|
||||
@@ -4234,7 +4234,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-engine"
|
||||
version = "0.18.2"
|
||||
version = "0.18.0"
|
||||
dependencies = [
|
||||
"log",
|
||||
"schemars",
|
||||
@@ -4253,7 +4253,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-geom"
|
||||
version = "0.18.2"
|
||||
version = "0.18.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -4262,7 +4262,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-gpu"
|
||||
version = "0.18.2"
|
||||
version = "0.18.0"
|
||||
dependencies = [
|
||||
"log",
|
||||
"naga",
|
||||
@@ -4279,7 +4279,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-io"
|
||||
version = "0.18.2"
|
||||
version = "0.18.0"
|
||||
dependencies = [
|
||||
"cadmpeg-core",
|
||||
"cadmpeg-ir",
|
||||
@@ -4302,7 +4302,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-kernel"
|
||||
version = "0.18.2"
|
||||
version = "0.18.0"
|
||||
dependencies = [
|
||||
"log",
|
||||
"proptest",
|
||||
@@ -4322,7 +4322,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-mcp"
|
||||
version = "0.18.2"
|
||||
version = "0.18.0"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
"solidcraft-engine",
|
||||
@@ -4331,7 +4331,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-render"
|
||||
version = "0.18.2"
|
||||
version = "0.18.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"moxcms",
|
||||
@@ -4345,7 +4345,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-sketch"
|
||||
version = "0.18.2"
|
||||
version = "0.18.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -4356,14 +4356,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-space-mouse"
|
||||
version = "0.18.2"
|
||||
version = "0.18.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-ui-egui"
|
||||
version = "0.18.2"
|
||||
version = "0.18.0"
|
||||
dependencies = [
|
||||
"arboard",
|
||||
"egui",
|
||||
@@ -4390,7 +4390,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-web"
|
||||
version = "0.18.2"
|
||||
version = "0.18.0"
|
||||
dependencies = [
|
||||
"eframe",
|
||||
"egui",
|
||||
@@ -5920,7 +5920,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
|
||||
|
||||
[[package]]
|
||||
name = "xtask"
|
||||
version = "0.18.2"
|
||||
version = "0.18.0"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ members = ["crates/*", "apps/*", "xtask"]
|
||||
exclude = ["vendor"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.18.2"
|
||||
version = "0.18.0"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
|
||||
@@ -59,34 +59,6 @@ pub fn make_id(ms: u64, random: u64) -> String {
|
||||
format!("{ms:x}-{random:x}")
|
||||
}
|
||||
|
||||
/// How long a remembered file may go unused, and unreferenced by the recent designs and the
|
||||
/// autosave, before the browser's copy of its handle is dropped.
|
||||
pub const HANDLE_MAX_AGE_MS: f64 = 90.0 * 24.0 * 3600.0 * 1000.0;
|
||||
|
||||
/// What to do with the remembered handles.
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
pub struct PrunePlan {
|
||||
/// Handles to forget.
|
||||
pub delete: Vec<String>,
|
||||
/// Handles seen unused for the first time: start their clock.
|
||||
pub stamp: Vec<String>,
|
||||
}
|
||||
|
||||
/// Decide which of the remembered handles `ids` (id, when it was last stamped) to forget: those
|
||||
/// that no recent design or autosave (`keep`) names and that have gone unused for `max_age`. One
|
||||
/// never stamped starts its clock now, so a file another tab has just saved is never dropped.
|
||||
pub fn plan_prune(ids: &[(String, Option<f64>)], keep: &std::collections::HashSet<String>, now: f64, max_age: f64) -> PrunePlan {
|
||||
let mut plan = PrunePlan::default();
|
||||
for (id, stamped) in ids.iter().filter(|(id, _)| !keep.contains(id)) {
|
||||
match stamped {
|
||||
None => plan.stamp.push(id.clone()),
|
||||
Some(at) if now - at > max_age => plan.delete.push(id.clone()),
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
plan
|
||||
}
|
||||
|
||||
/// Where a design saved with Save As goes.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum SaveTarget {
|
||||
@@ -140,7 +112,7 @@ mod web {
|
||||
use wasm_bindgen_futures::{JsFuture, spawn_local};
|
||||
use web_sys::{FileSystemFileHandle, IdbDatabase, IdbObjectStore, IdbOpenDbRequest, IdbRequest, IdbTransactionMode};
|
||||
|
||||
use super::{HANDLE_MAX_AGE_MS, is_abort, make_id, opens_design, parse, path, plan_prune, save_type};
|
||||
use super::{is_abort, make_id, opens_design, parse, path, save_type};
|
||||
use crate::files::{Files, err, read_handle};
|
||||
|
||||
const DB: &str = "solidcraft-disk-handles";
|
||||
@@ -425,106 +397,10 @@ mod web {
|
||||
db.transaction_with_str_and_mode(STORE, mode).map_err(err)?.object_store(STORE).map_err(err)
|
||||
}
|
||||
|
||||
/// Key of the time a handle was last used (the handle's own key is its id).
|
||||
fn stamp_key(id: &str) -> String {
|
||||
format!("at:{id}")
|
||||
}
|
||||
|
||||
async fn remember(id: &str, handle: &FileSystemFileHandle) -> Result<(), String> {
|
||||
let db = open_db().await?;
|
||||
let store = store(&db, IdbTransactionMode::Readwrite)?;
|
||||
result(&store.put_with_key(handle, &id.into()).map_err(err)?).await?;
|
||||
result(&store.put_with_key(&js_sys::Date::now().into(), &stamp_key(id).into()).map_err(err)?).await.map(|_| ())
|
||||
}
|
||||
|
||||
/// Note that the file was used now.
|
||||
async fn touch(id: &str) {
|
||||
let Ok(db) = open_db().await else { return };
|
||||
if let Ok(store) = store(&db, IdbTransactionMode::Readwrite)
|
||||
&& let Ok(req) = store.put_with_key(&js_sys::Date::now().into(), &stamp_key(id).into())
|
||||
{
|
||||
let _ = result(&req).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// The ids of every remembered file.
|
||||
pub async fn known_ids() -> Result<Vec<String>, String> {
|
||||
let db = open_db().await?;
|
||||
let req = store(&db, IdbTransactionMode::Readonly)?.get_all_keys().map_err(err)?;
|
||||
let keys: Array = result(&req).await?.dyn_into().map_err(|_| "no keys".to_string())?;
|
||||
Ok(keys.iter().filter_map(|k| k.as_string()).filter(|k| !k.starts_with("at:")).collect())
|
||||
}
|
||||
|
||||
async fn forget(ids: &[String]) -> Result<(), String> {
|
||||
let db = open_db().await?;
|
||||
let store = store(&db, IdbTransactionMode::Readwrite)?;
|
||||
for id in ids {
|
||||
result(&store.delete(&id.as_str().into()).map_err(err)?).await?;
|
||||
result(&store.delete(&stamp_key(id).into()).map_err(err)?).await?;
|
||||
HANDLES.with(|h| h.borrow_mut().remove(id));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Forget the remembered files nothing refers to any more (`keep`: the ids the recent designs
|
||||
/// and the autosave name), once they have gone unused for a long while.
|
||||
pub fn prune(keep: std::collections::HashSet<String>) {
|
||||
spawn_local(async move {
|
||||
let r = async {
|
||||
// A transaction ends when the page awaits anything but its own requests, so each
|
||||
// step opens its own.
|
||||
let known = known_ids().await?;
|
||||
let db = open_db().await?;
|
||||
let reading = store(&db, IdbTransactionMode::Readonly)?;
|
||||
let mut ids = Vec::new();
|
||||
for id in known {
|
||||
let at = result(&reading.get(&stamp_key(&id).into()).map_err(err)?).await?.as_f64();
|
||||
ids.push((id, at));
|
||||
}
|
||||
let plan = plan_prune(&ids, &keep, js_sys::Date::now(), HANDLE_MAX_AGE_MS);
|
||||
for id in &plan.stamp {
|
||||
touch(id).await;
|
||||
}
|
||||
forget(&plan.delete).await
|
||||
};
|
||||
if let Err(e) = r.await {
|
||||
log::warn!("remembered files weren't tidied: {e}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Open a design remembered from an earlier session (a recent one, after a reload): ask once
|
||||
/// for access to the file (call in the click), read it into the engine's files and queue it
|
||||
/// to open. A file that is gone is forgotten and dropped from the recent designs.
|
||||
pub fn restore(files: &Rc<Files>, path: &str) {
|
||||
let Some((id, name)) = parse(path) else { return };
|
||||
let (files, path, id, name) = (files.clone(), path.to_string(), id.to_string(), name.to_string());
|
||||
spawn_local(async move {
|
||||
let r = async {
|
||||
let handle = handle_for(&id).await?;
|
||||
ensure_readwrite(&handle).await?;
|
||||
read_handle(&handle).await
|
||||
};
|
||||
match r.await {
|
||||
Ok(bytes) => {
|
||||
vfs::insert(&path, bytes);
|
||||
files.opened.borrow_mut().push(path);
|
||||
files.wake();
|
||||
touch(&id).await;
|
||||
}
|
||||
Err(e) => {
|
||||
let gone = e.contains("NotFoundError") || e.contains("could not be found") || e.contains("no longer remembers");
|
||||
if gone {
|
||||
let _ = forget(std::slice::from_ref(&id)).await;
|
||||
files.disk_known.borrow_mut().remove(&id);
|
||||
files.gone.borrow_mut().push(path);
|
||||
files.say(format!("{name} isn't where it was saved any more"), true);
|
||||
} else {
|
||||
files.say(format!("{name}: {e}"), true);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
let req = store(&db, IdbTransactionMode::Readwrite)?.put_with_key(handle, &id.into()).map_err(err)?;
|
||||
result(&req).await.map(|_| ())
|
||||
}
|
||||
|
||||
async fn recall(id: &str) -> Result<Option<JsValue>, String> {
|
||||
@@ -579,22 +455,6 @@ mod tests {
|
||||
assert_eq!(route("/upload/part.step"), WriteTo::Memory);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_unreferenced_handles_unused_for_long_are_forgotten() {
|
||||
let keep: std::collections::HashSet<String> = ["recent".to_string()].into();
|
||||
let day = 24.0 * 3600.0 * 1000.0;
|
||||
let now = 1000.0 * day;
|
||||
let ids = vec![
|
||||
("recent".to_string(), Some(now - 200.0 * day)),
|
||||
("old".to_string(), Some(now - 100.0 * day)),
|
||||
("fresh".to_string(), Some(now - 5.0 * day)),
|
||||
("unstamped".to_string(), None),
|
||||
];
|
||||
let plan = plan_prune(&ids, &keep, now, HANDLE_MAX_AGE_MS);
|
||||
assert_eq!(plan, PrunePlan { delete: vec!["old".to_string()], stamp: vec!["unstamped".to_string()] });
|
||||
assert_eq!(plan_prune(&[], &keep, now, HANDLE_MAX_AGE_MS), PrunePlan::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handle_ids_differ_by_time_and_by_chance() {
|
||||
assert_ne!(make_id(1, 5), make_id(2, 5));
|
||||
|
||||
@@ -57,10 +57,6 @@ pub struct Files {
|
||||
pub incoming: RefCell<Vec<(String, Vec<u8>, Intent)>>,
|
||||
/// Designs opened from the computer's disk: their paths in the engine's files.
|
||||
pub opened: RefCell<Vec<String>>,
|
||||
/// The ids of the files remembered from earlier sessions (see `disk::restore`).
|
||||
pub disk_known: RefCell<std::collections::HashSet<String>>,
|
||||
/// Recent designs whose file is gone: to drop from the recent list.
|
||||
pub gone: RefCell<Vec<String>>,
|
||||
/// Disk designs whose last write failed: they are not saved.
|
||||
pub unsaved: RefCell<Vec<String>>,
|
||||
/// Messages for the status line (errors and confirmations).
|
||||
@@ -94,7 +90,7 @@ impl Files {
|
||||
}
|
||||
|
||||
/// Run a frame (the app sleeps until something happens).
|
||||
pub fn wake(&self) {
|
||||
fn wake(&self) {
|
||||
if let Some(c) = self.ctx.borrow().as_ref() {
|
||||
c.request_repaint();
|
||||
}
|
||||
@@ -271,10 +267,6 @@ pub fn start(files: &Rc<Files>) {
|
||||
}
|
||||
let files = files.clone();
|
||||
spawn_local(async move {
|
||||
match disk::known_ids().await {
|
||||
Ok(ids) => files.disk_known.borrow_mut().extend(ids),
|
||||
Err(e) => log::info!("no remembered files: {e}"),
|
||||
}
|
||||
match read_all().await {
|
||||
Ok(all) => {
|
||||
if local_only() {
|
||||
|
||||
@@ -136,11 +136,6 @@ mod web {
|
||||
self.app.open_path(&path);
|
||||
self.files.panel.set(false);
|
||||
}
|
||||
// Recent designs whose file is gone are dropped from the list.
|
||||
for path in self.files.gone.borrow_mut().drain(..) {
|
||||
self.app.home.recent.retain(|r| *r != path);
|
||||
self.app.home.opened_at.remove(&path);
|
||||
}
|
||||
for (text, error) in self.files.messages.borrow_mut().drain(..) {
|
||||
self.app.set_status(text, error);
|
||||
}
|
||||
@@ -208,9 +203,7 @@ mod web {
|
||||
let mut entries = self.files.entries.borrow().clone();
|
||||
entries.sort_by(|a, b| b.modified.total_cmp(&a.modified));
|
||||
let recent = &mut self.app.home.recent;
|
||||
let known = self.files.disk_known.borrow().clone();
|
||||
// A design on the computer's disk stays listed while its file is remembered.
|
||||
recent.retain(|p| vfs::exists(p) || disk::parse(p).is_some_and(|(id, _)| known.contains(id)));
|
||||
recent.retain(|p| vfs::exists(p));
|
||||
for e in entries.iter().filter(|e| solidcraft_engine::io::is_design_path(&e.name)) {
|
||||
let p = format!("{}{}", files::OPFS, e.name);
|
||||
if !recent.contains(&p) {
|
||||
@@ -218,10 +211,6 @@ mod web {
|
||||
}
|
||||
}
|
||||
recent.truncate(solidcraft_ui_egui::home::MAX_RECENT);
|
||||
// Remembered files that no recent design or autosave names are forgotten in time.
|
||||
let recovered = self.files.recovery.borrow().as_ref().and_then(|(_, p)| p.clone());
|
||||
let keep = recent.iter().chain(recovered.as_ref()).filter_map(|p| disk::parse(p)).map(|(id, _)| id.to_string()).collect();
|
||||
disk::prune(keep);
|
||||
}
|
||||
|
||||
/// The stored designs: open, insert, rename, delete, download; open from the computer.
|
||||
@@ -574,7 +563,6 @@ mod web {
|
||||
let files = Rc::new(Files::default());
|
||||
files::start(&files);
|
||||
let (panel, opener, saver, shown) = (files.clone(), files.clone(), files.clone(), files.clone());
|
||||
let (restorable, restorer) = (files.clone(), files.clone());
|
||||
let services = Services {
|
||||
// Open shows the browser's open dialog for a design where it has one
|
||||
// (the file keeps its handle, so Save writes back to it); otherwise,
|
||||
@@ -599,12 +587,6 @@ mod web {
|
||||
SaveTarget::Download => Box::pin(std::future::ready(Some(format!("{}{name}", files::DOWNLOADS)))),
|
||||
}
|
||||
})),
|
||||
// A recent design on the disk, from an earlier session, opens by asking
|
||||
// the browser for its remembered file.
|
||||
can_restore: Some(Box::new(move |path: &str| {
|
||||
disk::parse(path).is_some_and(|(id, _)| restorable.disk_known.borrow().contains(id))
|
||||
})),
|
||||
restore_file: Some(Box::new(move |path: &str| disk::restore(&restorer, path))),
|
||||
download_design: Some(Box::new(files::download)),
|
||||
browser_files: Some(Box::new(move || shown.panel.set(true))),
|
||||
install_app: Some(crate::install::service(&cc.egui_ctx)),
|
||||
|
||||
@@ -210,8 +210,6 @@ fn services(cc: &eframe::CreationContext<'_>) -> Services {
|
||||
http_download: Some(std::sync::Arc::new(http_download)),
|
||||
// Already an installed app: only the browser build offers to install.
|
||||
install_app: None,
|
||||
can_restore: None,
|
||||
restore_file: None,
|
||||
download_design: None,
|
||||
browser_files: None,
|
||||
agent_http: Some(std::sync::Arc::new(agent_http)),
|
||||
|
||||
@@ -141,13 +141,18 @@ new false
|
||||
normal false
|
||||
offset false
|
||||
offset_face false
|
||||
offset_one_side false
|
||||
offset_symmetric false
|
||||
offset_two_sides false
|
||||
open false
|
||||
orbit false
|
||||
origin false
|
||||
pan false
|
||||
params false
|
||||
paste false
|
||||
pattern_center false
|
||||
pattern_circ false
|
||||
pattern_flip false
|
||||
pattern_path false
|
||||
pattern_rect false
|
||||
perforate false
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
{
|
||||
"Center X": "Centre X",
|
||||
"Center Y": "Centre Y",
|
||||
"Center of mass": "Centre of mass",
|
||||
"Customize Toolbar": "Customise Toolbar",
|
||||
"Mass Center": "Mass Centre",
|
||||
"Modeled": "Modelled",
|
||||
"cmd.construct_point_center": "Point At Centre Of Circle/Sphere/Torus",
|
||||
"cmd.inspect_center_of_mass": "Centre of Mass",
|
||||
"cmd.sketch_arc_center_point": "Centre Point Arc",
|
||||
"cmd.sketch_circle_center": "Centre Diameter Circle",
|
||||
"cmd.sketch_rectangle_center": "Centre Rectangle",
|
||||
"cmd.sketch_slot_arc_center": "Centre Point Arc Slot",
|
||||
"cmd.sketch_slot_center_point": "Centre Point Slot",
|
||||
"cmd.sketch_slot_center_to_center": "Centre to Centre Slot",
|
||||
"pattern.alignment_hint": "Counts include the original. Centre balances copies; Flip chooses the extra side for even totals.",
|
||||
"render.opaque_preview_help": "Opaque PBR and simple colours; blended transparency. Refraction, HDRI and final rendering are not available yet.",
|
||||
"sketch_text.align_center": "Centre",
|
||||
"ui.center": "Centre",
|
||||
"ui.centerline": "Centreline",
|
||||
"ui.customizeToolbar": "Customise Toolbar…",
|
||||
"ui.design_properties.license": "Licence",
|
||||
"ui.design_properties.organization": "Organisation",
|
||||
"ui.space_mouse_step_pull": "Pull the cap towards you, hold it, then let go.",
|
||||
"ui.zoom_to_cursor_tip": "The wheel zooms towards the point under the cursor (off: towards the view's centre)",
|
||||
"update.prefs_flatpak": "Flatpak updates this copy ({version}): run {command} or use your software centre. SolidCraft doesn't check."
|
||||
}
|
||||
@@ -855,12 +855,6 @@
|
||||
"help.licences": "Licences",
|
||||
"help.mit": "MIT licence",
|
||||
"help.notice": "NOTICE",
|
||||
"help.solid.chamfer": "Cuts the selected edges with a flat bevel of the distance you set. Use it to break sharp edges or to ease the entry of a pin or screw.",
|
||||
"help.solid.extrude": "Pushes a sketch profile into 3D along a distance, adding or removing material. Use it to turn a flat outline into a block, a boss or a pocket.",
|
||||
"help.solid.fillet": "Rounds the selected edges with a smooth circular blend of the radius you set. Use it to soften sharp edges for strength, comfort or looks.",
|
||||
"help.solid.hole": "Drills a round hole of the diameter you set at a chosen point on a face. Use it for screw clearances, pins and other simple round openings.",
|
||||
"help.solid.revolve": "Spins a sketch profile around an axis to make a round solid. Use it for shafts, knobs, bowls and any part that is round about a centre line.",
|
||||
"help.solid.shell": "Hollows out a solid, leaving walls of the thickness you set, and can open the faces you pick. Use it for boxes, covers and other thin-walled parts.",
|
||||
"help.third_party": "Third-party licences",
|
||||
"home.documentation": "Documentation",
|
||||
"home.in_this_browser": "in this browser",
|
||||
|
||||
@@ -855,12 +855,6 @@
|
||||
"help.licences": "Licences",
|
||||
"help.mit": "Licence MIT",
|
||||
"help.notice": "NOTICE",
|
||||
"help.solid.chamfer": "Coupe les arêtes sélectionnées par un biseau plat de la distance indiquée. À utiliser pour casser des arêtes vives ou faciliter l'entrée d'une goupille ou d'une vis.",
|
||||
"help.solid.extrude": "Pousse le profil d'une esquisse en 3D sur une distance, en ajoutant ou en retirant de la matière. À utiliser pour transformer un contour plat en bloc, en bossage ou en poche.",
|
||||
"help.solid.fillet": "Arrondit les arêtes sélectionnées par un raccord circulaire lisse du rayon indiqué. À utiliser pour adoucir des arêtes vives par souci de solidité, de confort ou d'aspect.",
|
||||
"help.solid.hole": "Perce un trou rond du diamètre indiqué en un point choisi d'une face. À utiliser pour les passages de vis, les goupilles et autres ouvertures rondes simples.",
|
||||
"help.solid.revolve": "Fait tourner le profil d'une esquisse autour d'un axe pour obtenir un solide de révolution. À utiliser pour les arbres, boutons, bols et toute pièce ronde autour d'une ligne centrale.",
|
||||
"help.solid.shell": "Évide un solide en laissant des parois de l'épaisseur indiquée, et peut ouvrir les faces choisies. À utiliser pour les boîtes, couvercles et autres pièces à parois minces.",
|
||||
"help.third_party": "Licences tierces",
|
||||
"home.documentation": "Documentation",
|
||||
"home.in_this_browser": "dans ce navigateur",
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -855,12 +855,6 @@
|
||||
"help.licences": "ライセンス",
|
||||
"help.mit": "MITライセンス",
|
||||
"help.notice": "NOTICE",
|
||||
"help.solid.chamfer": "選択した辺を、指定した距離で平らに斜めに削ります。鋭い角を落とすときや、ピンやねじを入れやすくするときに使います。",
|
||||
"help.solid.extrude": "スケッチの輪郭を指定した距離だけ立体方向に押し出し、材料を足したり削ったりします。平面の図形をブロック、突起、ポケットにするときに使います。",
|
||||
"help.solid.fillet": "選択した辺を、指定した半径のなめらかな円弧で丸めます。強度や持ちやすさ、見た目のために鋭い角を和らげるときに使います。",
|
||||
"help.solid.hole": "面上の指定した位置に、指定した直径の丸い穴をあけます。ねじのクリアランスやピン穴など、単純な丸い開口に使います。",
|
||||
"help.solid.revolve": "スケッチの輪郭を軸のまわりに回転させ、丸い立体を作ります。軸、つまみ、ボウルなど、中心線まわりに丸い部品に使います。",
|
||||
"help.solid.shell": "立体の中をくり抜き、指定した厚さの壁を残します。選んだ面を開口にすることもできます。箱、カバーなどの薄肉の部品に使います。",
|
||||
"help.third_party": "サードパーティライセンス",
|
||||
"home.documentation": "ドキュメント",
|
||||
"home.in_this_browser": "このブラウザ内",
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -855,12 +855,6 @@
|
||||
"help.licences": "许可证",
|
||||
"help.mit": "MIT 许可证",
|
||||
"help.notice": "NOTICE",
|
||||
"help.solid.chamfer": "用指定的距离在所选边上切出一个平直的斜面。用于去除锐边,或使销钉、螺钉更容易插入。",
|
||||
"help.solid.extrude": "将草图轮廓按指定距离拉伸为三维形体,可以增加或去除材料。用于把平面轮廓变成方块、凸台或凹槽。",
|
||||
"help.solid.fillet": "用指定半径的平滑圆弧将所选的边倒圆。用于出于强度、手感或外观的考虑而柔化锐边。",
|
||||
"help.solid.hole": "在面上的指定位置钻出指定直径的圆孔。用于螺钉过孔、销孔等简单的圆形开口。",
|
||||
"help.solid.revolve": "将草图轮廓绕一条轴旋转,生成圆形的实体。用于轴、旋钮、碗等围绕中心线呈圆形的零件。",
|
||||
"help.solid.shell": "将实体掏空,留下指定厚度的壁,还可以打开所选的面。用于盒子、盖子等薄壁零件。",
|
||||
"help.third_party": "第三方许可证",
|
||||
"home.documentation": "文档",
|
||||
"home.in_this_browser": "在此浏览器中",
|
||||
|
||||
@@ -3387,84 +3387,6 @@ struct ExtrudeConstructor {
|
||||
interval: (f64, f64),
|
||||
}
|
||||
|
||||
/// The tool of an Extrude whose profile is a whole planar face of its one target (the face's
|
||||
/// outline projected into the sketch), started at the face (#2040). The projection fits an edge
|
||||
/// that is no line or arc, so the profile's tool lies a hair off the body all round its outline,
|
||||
/// and the boolean fails there. A join takes the body's own face swept instead, which is sewn on
|
||||
/// along it. A cut whose walls take nothing from the body (all of it within the depth lies over
|
||||
/// the face) takes a slab beyond the depth plane instead, which meets the body only across that
|
||||
/// plane; one whose walls cut into the body at some edges keeps those walls, exactly, and moves
|
||||
/// the others off it (`kernel::cut_tool`). `None` (the profile's own tool) otherwise. With the
|
||||
/// interval along the normal it spans.
|
||||
fn whole_face_tool(
|
||||
st: &ModelState,
|
||||
targets: &[String],
|
||||
ss: &SolvedSketch,
|
||||
r: &Region2,
|
||||
operation: Operation,
|
||||
lo: f64,
|
||||
hi: f64,
|
||||
) -> Option<(Traced, (f64, f64))> {
|
||||
if !matches!(operation, Operation::Join | Operation::Cut) || hi - lo <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
// An outline of lines and arcs is the face's own: the profile's tool already meets the body
|
||||
// exactly, and keeps the names later features attach to (#489).
|
||||
if r.outer.segs.iter().all(|s| matches!(s, solidcraft_geom::Seg2::Line { .. } | solidcraft_geom::Seg2::Arc { .. })) {
|
||||
return None;
|
||||
}
|
||||
let mut candidates = st.bodies.iter().filter(|b| targets.is_empty() || targets.contains(&b.name));
|
||||
let target = candidates.next()?;
|
||||
if candidates.next().is_some() {
|
||||
return None;
|
||||
}
|
||||
let face = kernel::matching_face(&target.body, &ss.plane, r, &[lo, hi])?;
|
||||
let n = ss.plane.normal();
|
||||
let tol = target.body.size() * 1e-6 + 1e-9;
|
||||
let up = face.normal.dot(n) > 0.0;
|
||||
let (at_lo, at_hi) = ((face.height - lo).abs() <= tol, (face.height - hi).abs() <= tol);
|
||||
let roles = |region| crate::lineage::ProfileRoles {
|
||||
sketch: Some(ss),
|
||||
region: Some(region),
|
||||
caps: [Some(crate::lineage::extrude_cap_role(lo)), Some(crate::lineage::extrude_cap_role(hi))],
|
||||
};
|
||||
match operation {
|
||||
// Out of the body from the face.
|
||||
Operation::Join if (up && at_lo) || (!up && at_hi) => {
|
||||
let built = centered_extrude(&ss.plane, r, lo, hi, Some(ss)).ok()?;
|
||||
let [built] = built.as_slice() else { return None };
|
||||
let exact = kernel::face_prism(&target.body, face, hi - lo, true, &built.body).ok()?;
|
||||
kernel::can_join_touching_faces(&target.body, &exact).then(|| (roles(r).tool(exact, Some(&built.body)), (lo, hi)))
|
||||
}
|
||||
// Into the body from the face, its walls touching it at most.
|
||||
Operation::Cut if ((up && at_hi) || (!up && at_lo)) && !kernel::cut_takes_only_the_face(&target.body, face, hi - lo) => {
|
||||
// Some walls go into the body: those that only touch it are moved off.
|
||||
let built = centered_extrude(&ss.plane, r, lo, hi, Some(ss)).ok()?;
|
||||
let [built] = built.as_slice() else { return None };
|
||||
let (tool, off) = kernel::cut_tool(&target.body, face, hi - lo, Some(&built.body))?;
|
||||
let span = if up { (lo, hi + off) } else { (lo - off, hi) };
|
||||
Some((roles(r).tool(tool, Some(&built.body)), span))
|
||||
}
|
||||
Operation::Cut if (up && at_hi) || (!up && at_lo) => {
|
||||
// Over the whole body, from the depth plane out past it.
|
||||
let reach = target.body.size() * 2.0 + (hi - lo);
|
||||
let c = r.outer.centroid();
|
||||
let p = |x: f64, y: f64| Vec2::new(c.x + x * reach, c.y + y * reach);
|
||||
let line = |a: Vec2, b: Vec2| solidcraft_geom::Seg2::Line { a, b };
|
||||
let corners = [p(-1.0, -1.0), p(1.0, -1.0), p(1.0, 1.0), p(-1.0, 1.0)];
|
||||
let segs = (0..4).filter_map(|i| Some(line(*corners.get(i)?, *corners.get((i + 1) % 4)?))).collect();
|
||||
let slab = Region2 { outer: solidcraft_geom::Loop2 { segs }, holes: vec![] };
|
||||
let (l, h) = if up { (lo, hi + reach) } else { (lo - reach, hi) };
|
||||
let built = centered_extrude(&ss.plane, &slab, l, h, None).ok()?;
|
||||
let [built] = built.as_slice() else { return None };
|
||||
#[cfg(test)]
|
||||
whole_face_tests::slab_taken();
|
||||
Some((roles(&slab).tool(built.body.clone(), None), (l, h)))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Construct planar caps locally before placing the completed tool.
|
||||
fn centered_extrude(plane: &Plane, region: &Region2, start: f64, end: f64, sketch: Option<&SolvedSketch>) -> Result<Vec<Traced>> {
|
||||
if !plane.origin.is_finite()
|
||||
@@ -3774,15 +3696,6 @@ fn feature_tools_with_constructor(
|
||||
None
|
||||
};
|
||||
for r in regions.iter().filter(|_| !touching_batch) {
|
||||
if regions.len() == 1
|
||||
&& let Some((tool, (l2, h2))) = whole_face_tool(st, &plain_targets, &ss, r, *operation, lo + off, hi + off)
|
||||
{
|
||||
untrimmed &= l2 == lo + off && h2 == hi + off;
|
||||
tools.push(tool);
|
||||
footprints.push(r.clone());
|
||||
extents.push((l2, h2));
|
||||
continue;
|
||||
}
|
||||
if *operation == Operation::Join {
|
||||
let exact = centered_extrude(&ss.plane, r, lo + off, hi + off, Some(&ss))?;
|
||||
if exact.iter().all(|tool| {
|
||||
@@ -4776,11 +4689,6 @@ fn replay(
|
||||
// A primitive's or a hole's targets are its participants (#1108): the copies change
|
||||
// those bodies only, like the feature itself (#2755).
|
||||
let targets = if targets.is_empty() { src.participants.clone() } else { targets };
|
||||
// A join that merged its targets left only the first of them (the others now live in
|
||||
// it): the copies change the bodies still there (#3378). When none is, the names stay
|
||||
// and say which body is missing.
|
||||
let present: Vec<String> = targets.iter().filter(|t| st.bodies.iter().any(|b| &b.name == *t)).cloned().collect();
|
||||
let targets = if present.is_empty() { targets } else { present };
|
||||
let mut copies = Vec::new();
|
||||
if let FeatureKind::Hole { diameter, depth, hole, to, .. } = &src.kind {
|
||||
// A hole is drilled again at each copy of its spot (found on the surface there), so
|
||||
@@ -6401,10 +6309,6 @@ mod chain_tests {
|
||||
#[path = "eval_cost_tests.rs"]
|
||||
mod cost_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "eval_whole_face_tests.rs"]
|
||||
mod whole_face_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod body_name_tests {
|
||||
use super::*;
|
||||
|
||||
@@ -1,85 +0,0 @@
|
||||
//! Extrudes from a whole face whose outline is no lines and arcs (#2040), checked through the
|
||||
//! tool `whole_face_tool` picks.
|
||||
|
||||
use std::cell::Cell;
|
||||
|
||||
use serde_json::json;
|
||||
use solidcraft_geom::{Plane, Vec2, Vec3};
|
||||
use solidcraft_kernel as kernel;
|
||||
use solidcraft_sketch::{CurveKind, Sketch};
|
||||
|
||||
use crate::*;
|
||||
|
||||
thread_local! {
|
||||
static SLABS: Cell<usize> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
/// A cut took a slab over the whole body as its tool, on this thread.
|
||||
pub(super) fn slab_taken() {
|
||||
SLABS.with(|n| n.set(n.get() + 1));
|
||||
}
|
||||
|
||||
/// A closed spline through six points round the origin, on the plane at height `z`.
|
||||
fn spline_sketch(z: f64) -> FeatureKind {
|
||||
let mut sk = Sketch::new();
|
||||
let fit = [(8.0, 0.0), (4.0, 6.0), (-3.0, 7.0), (-7.0, 1.0), (-4.0, -6.0), (3.0, -5.0)];
|
||||
let mut pts: Vec<usize> = fit.iter().map(|&(x, y)| sk.add_point(Vec2::new(x, y), None).unwrap()).collect();
|
||||
pts.push(pts[0]);
|
||||
sk.add_curve(CurveKind::Spline { pts, control: false, degree: 3, periodic: true }, None).unwrap();
|
||||
let plane = Plane { origin: Vec3::new(0.0, 0.0, z), ..Plane::XY };
|
||||
FeatureKind::Sketch { plane: PlaneRef::Custom { plane }, sketch: sk }
|
||||
}
|
||||
|
||||
fn extrude(doc: &mut Document, sketch: u64, extent: serde_json::Value, operation: Operation) {
|
||||
let kind = FeatureKind::Extrude {
|
||||
thin: None,
|
||||
sketch: SketchId(sketch),
|
||||
profiles: ProfileSel::All,
|
||||
extent: serde_json::from_value(extent).unwrap(),
|
||||
operation,
|
||||
targets: vec![],
|
||||
};
|
||||
doc.add_feature(kind, None).unwrap();
|
||||
}
|
||||
|
||||
fn volume(model: &Model) -> f64 {
|
||||
let state = model.state();
|
||||
assert!(model.results.iter().all(|r| r.error.is_none()), "{:?}", model.results.iter().find(|r| r.error.is_some()));
|
||||
assert_eq!(state.bodies.len(), 1);
|
||||
assert!(state.bodies[0].body.validity().is_empty(), "{:?}", state.bodies[0].body.validity());
|
||||
kernel::measure(&state.bodies[0].body).unwrap().volume
|
||||
}
|
||||
|
||||
/// A prism 10 tall on a closed spline, standing on a 40 x 40 x 5 plate, cut 3 into its whole
|
||||
/// top face. The walls only touch the prism, so the cut takes a slab over the whole body from 3
|
||||
/// below the face up: it must take the face's area times 3 and leave the plate alone.
|
||||
#[test]
|
||||
fn slab_cut_into_a_spline_prism() {
|
||||
let mut doc = Document::new("spline prism");
|
||||
let plate = FeatureKind::Box {
|
||||
corner: point_expr(Vec3::new(-20.0, -20.0, 0.0)),
|
||||
length: "40 mm".into(),
|
||||
width: "40 mm".into(),
|
||||
height: "5 mm".into(),
|
||||
operation: Operation::NewBody,
|
||||
};
|
||||
doc.add_feature(plate, None).unwrap();
|
||||
let base = doc.add_feature(spline_sketch(5.0), None).unwrap();
|
||||
extrude(&mut doc, base, json!({"distance": "10 mm"}), Operation::Join);
|
||||
let mut model = Model::new();
|
||||
model.evaluate(&doc);
|
||||
let joined = volume(&model);
|
||||
let area = (joined - 40.0 * 40.0 * 5.0) / 10.0;
|
||||
assert!(area > 100.0, "the prism's area {area}");
|
||||
|
||||
let top = doc.add_feature(spline_sketch(15.0), None).unwrap();
|
||||
extrude(&mut doc, top, json!({"distance": "3 mm", "direction": "negative"}), Operation::Cut);
|
||||
SLABS.with(|n| n.set(0));
|
||||
model.evaluate(&doc);
|
||||
let cut = volume(&model);
|
||||
assert_eq!(SLABS.with(Cell::get), 1, "the cut took the slab");
|
||||
assert!((joined - cut - area * 3.0).abs() < 1e-3 * area, "took {}, expected {}", joined - cut, area * 3.0);
|
||||
let bounds = model.state().bodies[0].mesh().bounds();
|
||||
assert!((bounds.max.z - 12.0).abs() < 1e-6, "top at {}", bounds.max.z);
|
||||
assert!(bounds.min.dist(Vec3::new(-20.0, -20.0, 0.0)) < 1e-6, "plate from {:?}", bounds.min);
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
//! Faces that are picked as one (#3745 follow-up): a modelled thread is thousands of small faces
|
||||
//! (its flanks, and the pieces of the surface it was cut into), but it is one surface to point at,
|
||||
//! light and select; so are the pieces of one face an imported file had (a face wrapping all the
|
||||
//! way round, split in two for the kernel).
|
||||
//!
|
||||
//! The groups come from what made the faces, never from their shape: a face made by a Thread
|
||||
//! feature is named after it (`F<id>:…`), and a piece of a face the thread cut names it among the
|
||||
//! faces around it (`…[F<id>:…]`). Working the names out for a large body takes a while, so it is
|
||||
//! done on a worker thread, once per body, and asked for without waiting.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use crate::{Document, FeatureKind, ModelBody};
|
||||
|
||||
/// Each face's group (an index into `groups`), and the groups: faces picked together, in order.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct FaceGroups {
|
||||
of_face: Vec<Option<u32>>,
|
||||
groups: Vec<Arc<Vec<usize>>>,
|
||||
}
|
||||
|
||||
impl FaceGroups {
|
||||
/// The group of `face` (`None`: it is picked alone).
|
||||
pub fn group_of(&self, face: usize) -> Option<u32> {
|
||||
self.of_face.get(face).copied().flatten()
|
||||
}
|
||||
|
||||
/// The faces picked together with `face` (`None`: it is picked alone).
|
||||
pub fn of(&self, face: usize) -> Option<Arc<Vec<usize>>> {
|
||||
let g = self.of_face.get(face).copied().flatten()?;
|
||||
self.groups.get(g as usize).cloned()
|
||||
}
|
||||
|
||||
/// Work out the groups of `b` (the names of its faces are worked out here: slow for a big body).
|
||||
pub fn of_body(threads: &[u64], b: &ModelBody) -> FaceGroups {
|
||||
let mut keyed: HashMap<(u8, u64), Vec<usize>> = HashMap::new();
|
||||
if !threads.is_empty() {
|
||||
let names = crate::naming::face_names(b);
|
||||
let marks: Vec<(u64, String, String)> = threads.iter().map(|id| (*id, format!("F{id}:"), format!("[F{id}:"))).collect();
|
||||
for (i, name) in names.iter().enumerate() {
|
||||
// Made by the thread, or a piece of a face the thread cut (it names the thread's faces
|
||||
// around it).
|
||||
let own = |p: &str, inside: &str| name.starts_with(p) || name.contains(inside) || name.contains(&format!(",{p}"));
|
||||
if let Some((id, _, _)) = marks.iter().find(|(_, p, inside)| own(p, inside)) {
|
||||
keyed.entry((0, *id)).or_default().push(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Pieces of one face of an imported file.
|
||||
if let Some(sources) = b.body.face_sources() {
|
||||
for (i, s) in sources.iter().enumerate() {
|
||||
if let Some(solidcraft_kernel::FaceSource::Imported { face, .. }) = s
|
||||
&& !keyed.values().any(|faces| faces.contains(&i))
|
||||
{
|
||||
keyed.entry((1, *face)).or_default().push(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = FaceGroups { of_face: vec![None; b.body.face_count()], groups: Vec::new() };
|
||||
let mut groups: Vec<Vec<usize>> = keyed.into_values().filter(|faces| faces.len() > 1).collect();
|
||||
groups.sort();
|
||||
for faces in groups {
|
||||
let g = u32::try_from(out.groups.len()).unwrap_or(u32::MAX);
|
||||
for &f in &faces {
|
||||
if let Some(slot) = out.of_face.get_mut(f) {
|
||||
*slot = Some(g);
|
||||
}
|
||||
}
|
||||
out.groups.push(Arc::new(faces));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The modelled threads of `doc`, by feature id.
|
||||
pub fn thread_features(doc: &Document) -> Vec<u64> {
|
||||
doc.features.iter().filter(|f| matches!(f.kind, FeatureKind::Thread { modeled: true, .. })).map(|f| f.id).collect()
|
||||
}
|
||||
|
||||
/// Groups worked out (or being worked out: `None`), by the identity of a body's names and the
|
||||
/// threads they were grouped by.
|
||||
type Cache = HashMap<(usize, Vec<u64>), Option<Arc<FaceGroups>>>;
|
||||
static CACHE: Mutex<Option<Cache>> = Mutex::new(None);
|
||||
/// Bodies whose groups are kept; the oldest go first.
|
||||
const KEPT: usize = 256;
|
||||
|
||||
/// The groups of `b` in `doc` if they are worked out; otherwise they are worked out on a worker
|
||||
/// thread (once) and `None` comes back meanwhile. The browser build has no threads: there they
|
||||
/// are worked out now.
|
||||
pub fn face_groups_soon(doc: &Document, b: &ModelBody) -> Option<Arc<FaceGroups>> {
|
||||
let threads = thread_features(doc);
|
||||
if threads.is_empty() && b.body.face_sources().is_none() {
|
||||
return Some(Arc::new(FaceGroups::default()));
|
||||
}
|
||||
let key = (b.names.id(), threads.clone());
|
||||
{
|
||||
let Ok(mut cache) = CACHE.lock() else { return None };
|
||||
let cache = cache.get_or_insert_with(HashMap::new);
|
||||
if let Some(entry) = cache.get(&key) {
|
||||
return entry.clone();
|
||||
}
|
||||
if cache.len() >= KEPT {
|
||||
cache.clear();
|
||||
}
|
||||
cache.insert(key.clone(), None);
|
||||
}
|
||||
let work = move |b: ModelBody| {
|
||||
let groups = Arc::new(FaceGroups::of_body(&threads, &b));
|
||||
if let Ok(mut cache) = CACHE.lock()
|
||||
&& let Some(slot) = cache.as_mut().and_then(|c| c.get_mut(&key))
|
||||
{
|
||||
*slot = Some(groups.clone());
|
||||
}
|
||||
groups
|
||||
};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let body = b.clone();
|
||||
let work = work.clone();
|
||||
if std::thread::Builder::new().name("face-groups".into()).spawn(move || drop(work(body))).is_ok() {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(work(b.clone()))
|
||||
}
|
||||
@@ -22,6 +22,7 @@ mod document;
|
||||
mod eval;
|
||||
pub mod expr;
|
||||
pub mod face_anchor;
|
||||
pub mod face_groups;
|
||||
mod feature_geometry;
|
||||
mod feature_refs;
|
||||
pub use face_anchor::{FaceAnchor, FaceAttachmentStatus};
|
||||
|
||||
@@ -1150,76 +1150,3 @@ fn joined_loft_frames_reference_mesh_covers_each_face_once() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The block of #2040 with `extra` run after it.
|
||||
fn rounded_block_and(extra: Value) -> Session {
|
||||
let mut script: Value = serde_json::from_str(include_str!("../../../examples/regressions/extrude_face_rounded_by_fillets.json")).unwrap();
|
||||
script["commands"].as_array_mut().unwrap().push(extra);
|
||||
replay(&script.to_string())
|
||||
}
|
||||
|
||||
/// #2040: the slanted face of a block whose ends fillets round, extruded as a join. Its outline's
|
||||
/// quarter-ellipses come into the face's sketch as splines a hair off the body's edges, and the
|
||||
/// join failed with "boolean Union: no result"; it now sweeps the body's own face. It adds the
|
||||
/// face's area times its height: a 10 x 12 face less four corners of (1 - pi/4) r * r*sqrt(2).
|
||||
#[test]
|
||||
fn extrude_join_from_a_face_rounded_by_fillets() {
|
||||
let at = json!([16.191269086108846, -6.702792508916929, 4.676550460347439]);
|
||||
let before = volume(&replay(include_str!("../../../examples/regressions/extrude_face_rounded_by_fillets.json")), "Body1");
|
||||
let r = 3.8_f64;
|
||||
let area = 10.0 * 12.0 - 4.0 * (1.0 - std::f64::consts::FRAC_PI_4) * r * r * 2f64.sqrt();
|
||||
let joined = rounded_block_and(json!({"command": "solid.extrude", "params": {"face": at, "distance": 5, "operation": "join"}}));
|
||||
let bodies = &joined.model.state().bodies;
|
||||
assert_eq!(bodies.len(), 1, "the join makes no second body");
|
||||
assert!(bodies[0].body.validity().is_empty(), "{:?}", bodies[0].body.validity());
|
||||
let v = volume(&joined, "Body1");
|
||||
assert!((v - (before + area * 5.0)).abs() < 0.05, "join {v} expected {}", before + area * 5.0);
|
||||
}
|
||||
|
||||
/// #2040: a cut 3 mm into the slanted face of the block rounded along its top only (its bottom
|
||||
/// edge left sharp). The walls from the bottom edge go into the body and the others only touch
|
||||
/// it, along edges with curved faces beside them: the cut failed with "boolean Cut: no result".
|
||||
/// In the face's plane the body's section at depth t is the block's section (10 wide, h high, its
|
||||
/// top corners rounded) moved down the face by t: the cut takes
|
||||
/// √2 ∫₀³ (10 (h − t/√2) − 2 (1 − π/4) r²) dt.
|
||||
#[test]
|
||||
fn extrude_cut_into_a_face_beside_rounds() {
|
||||
let at = json!([16.191269086108846, -6.702792508916929, 4.676550460347439]);
|
||||
let top_only = |extra: Option<Value>| {
|
||||
let mut script: Value = serde_json::from_str(include_str!("../../../examples/regressions/extrude_face_rounded_by_fillets.json")).unwrap();
|
||||
let commands = script["commands"].as_array_mut().unwrap();
|
||||
let fillet = commands.last_mut().unwrap();
|
||||
fillet["params"]["edges"] = json!([[10, -10, 8.485281374238571], [10, 0, 8.485281374238571]]);
|
||||
commands.extend(extra);
|
||||
replay(&script.to_string())
|
||||
};
|
||||
let before = volume(&top_only(None), "Body1");
|
||||
let cut = top_only(Some(json!({"command": "solid.extrude", "params": {"face": at, "distance": 3, "direction": "negative", "operation": "cut"}})));
|
||||
let bodies = &cut.model.state().bodies;
|
||||
assert_eq!(bodies.len(), 1);
|
||||
assert!(bodies[0].body.validity().is_empty(), "{:?}", bodies[0].body.validity());
|
||||
let (h, r, d, w) = (8.485281374238571_f64, 3.8_f64, 3.0_f64, 10.0_f64);
|
||||
let corner = (1.0 - std::f64::consts::FRAC_PI_4) * r * r;
|
||||
let taken = 2f64.sqrt() * w * h * d - w * d * d / 2.0 - 2.0 * 2f64.sqrt() * corner * d;
|
||||
let v = before - volume(&cut, "Body1");
|
||||
assert!((v - taken).abs() < 0.05, "took {v}, expected {taken}");
|
||||
}
|
||||
|
||||
/// #2040: a cut 2 mm into the top face of the block rounded at its ends, the strip 10 − 2r wide
|
||||
/// between the rounds. Below the face the rounds stand out past its outline, so a slab over the
|
||||
/// whole body would take them too: the cut takes only what lies over the face, at height z from
|
||||
/// x = 0 to the slanted face at x = x0 + z.
|
||||
#[test]
|
||||
fn extrude_cut_into_a_rounded_block_top() {
|
||||
let (h, r, x0, d) = (8.485281374238571_f64, 3.8_f64, 11.514718625761429_f64, 2.0_f64);
|
||||
let before = volume(&replay(include_str!("../../../examples/regressions/extrude_face_rounded_by_fillets.json")), "Body1");
|
||||
let cut = rounded_block_and(
|
||||
json!({"command": "solid.extrude", "params": {"face": [5, -5, h], "distance": d, "direction": "negative", "operation": "cut"}}),
|
||||
);
|
||||
let bodies = &cut.model.state().bodies;
|
||||
assert_eq!(bodies.len(), 1);
|
||||
assert!(bodies[0].body.validity().is_empty(), "{:?}", bodies[0].body.validity());
|
||||
let taken = (10.0 - 2.0 * r) * (x0 * d + (h * h - (h - d) * (h - d)) / 2.0);
|
||||
let v = before - volume(&cut, "Body1");
|
||||
assert!((v - taken).abs() < 0.05, "took {v}, expected {taken}");
|
||||
}
|
||||
|
||||
@@ -20,11 +20,11 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.icon("open")
|
||||
.key("Ctrl+O")
|
||||
.noundo()
|
||||
.params("path: .solidcraft design, or a .step/.stp/.igs/.fcstd/.3dm/.3mf/.stl/.obj/.glb/.gltf file (STEP, IGES, FreeCAD, Rhino, 3MF, STL, OBJ or glTF; opens as a new design holding the file as a component named after it, as file.insert_step and file.insert_mesh make); up?: z|y for a STEP, IGES, FreeCAD, Rhino or glTF file (see file.insert_step and file.insert_mesh); names?: auto|solid|product|instance for a STEP, IGES, FreeCAD or Rhino file (see file.insert_step)"),
|
||||
.params("path: .solidcraft design, or a .step/.stp/.igs/.fcstd/.3dm/.3mf/.stl/.obj/.glb/.gltf file (STEP, IGES, FreeCAD, Rhino, 3MF, STL, OBJ or glTF; opens as a new design holding the file as a component named after it, as file.insert_step and file.insert_mesh make); up?: z|y for a STEP, IGES, FreeCAD, Rhino or glTF file (see file.insert_step and file.insert_mesh); names?: solid|product|instance for a STEP, IGES, FreeCAD or Rhino file (see file.insert_step)"),
|
||||
CommandSpec::new("file.insert_step", "Insert STEP", insert_step)
|
||||
.at("SOLID", "INSERT")
|
||||
.icon("import")
|
||||
.params("path: STEP, IGES, FreeCAD .FCStd or Rhino .3dm file (its bodies join the design as an Import base feature in a new component named after the file, placed in the active component; an assembly's products become nested components, a repeated part one component with an occurrence per placement, all held as one rigid group until component.unlock → component, component_name, occurrence, subcomponents?, rigid_joints?); name? (the feature's and the component's); up?: z|y (default z: the file's axes are kept; y: the file has Y up, so the import's component is turned a quarter turn about X, Y becoming Z → stand_up: its occurrence); names?: auto|solid|product|instance (default auto: keep meaningful solid names, replace placeholders with the nearest named product, else instance; solid: the solid's own name; product: the part's name; instance: the occurrence's name, else the product's); matrix?: [12 or 16 numbers] (where the new component's occurrence sits in the active component, after `up`: a rigid row-major 3x4 rotation-and-translation or 4x4 matrix, flat or as rows, as occurrence.move takes it; a scale, shear or mirror is refused before the file is read); tolerance? (see occurrence.move)"),
|
||||
.params("path: STEP, IGES, FreeCAD .FCStd or Rhino .3dm file (its bodies join the design as an Import base feature in a new component named after the file, placed in the active component; an assembly's products become nested components, a repeated part one component with an occurrence per placement, all held as one rigid group until component.unlock → component, component_name, occurrence, subcomponents?, rigid_joints?); name? (the feature's and the component's); up?: z|y (default z: the file's axes are kept; y: the file has Y up, so the import's component is turned a quarter turn about X, Y becoming Z → stand_up: its occurrence); names?: solid|product|instance (what the bodies are named after: the solid's own name, else the product's (default); the name of the product (part) that holds the body; the name of the assembly occurrence (instance), else the product's); matrix?: [12 or 16 numbers] (where the new component's occurrence sits in the active component, after `up`: a rigid row-major 3x4 rotation-and-translation or 4x4 matrix, flat or as rows, as occurrence.move takes it; a scale, shear or mirror is refused before the file is read); tolerance? (see occurrence.move)"),
|
||||
CommandSpec::new("file.insert_mesh", "Insert Mesh", insert_mesh)
|
||||
.at("SOLID", "INSERT")
|
||||
.icon("import")
|
||||
@@ -89,10 +89,9 @@ fn step_options(p: &Value, cmd: &str) -> Result<StepOptions> {
|
||||
};
|
||||
let names = match p.get("names") {
|
||||
None | Some(Value::Null) => solidcraft_io::StepNames::default(),
|
||||
Some(v) => v
|
||||
.as_str()
|
||||
.and_then(solidcraft_io::StepNames::parse)
|
||||
.ok_or_else(|| bad(cmd, "`names` must be \"auto\", \"solid\", \"product\" or \"instance\""))?,
|
||||
Some(v) => {
|
||||
v.as_str().and_then(solidcraft_io::StepNames::parse).ok_or_else(|| bad(cmd, "`names` must be \"solid\", \"product\" or \"instance\""))?
|
||||
}
|
||||
};
|
||||
Ok(StepOptions { y_up, names })
|
||||
}
|
||||
|
||||
@@ -549,29 +549,3 @@ fn copies_of_a_primitive_cut_only_its_targets() {
|
||||
assert!(rel(removed, holes * PI * 9.0 * 10.0) < 1e-3, "{id}: {removed} mm³ cut from Plaque");
|
||||
}
|
||||
}
|
||||
|
||||
/// #3378: a pattern or mirror of a join whose targets the join merged into one body copies onto
|
||||
/// that body, as before #2755, instead of looking for the target the join used up.
|
||||
#[test]
|
||||
fn copies_of_a_join_that_merged_its_targets_join_the_merged_body() {
|
||||
for (copy, n) in [
|
||||
(json!(["solid.pattern.circular", {"features": ["spoke"], "axis": "Y", "count": 5}]), 5.0),
|
||||
(json!(["solid.mirror", {"features": ["spoke"], "plane": {"origin": [0, 0, 0], "normal": [1, 0, 0]}}]), 2.0),
|
||||
] {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.cylinder", json!({"radius": 66, "height": 3, "base": [0, 0, 0], "axis": "Y", "body_name": "rim"}));
|
||||
run(&mut s, "solid.cylinder", json!({"radius": 63, "height": 3, "base": [0, 0, 0], "axis": "Y", "operation": "cut", "targets": ["rim"]}));
|
||||
run(&mut s, "solid.cylinder", json!({"radius": 12, "height": 3, "base": [0, 0, 0], "axis": "Y", "body_name": "hub"}));
|
||||
let v0 = volume(&mut s);
|
||||
let spoke = json!({"length": 52, "width": 3, "height": 2.5, "corner": [12, 0, -1.25], "operation": "join", "targets": ["rim", "hub"], "name": "spoke"});
|
||||
run(&mut s, "solid.box", spoke);
|
||||
let v1 = volume(&mut s);
|
||||
let (id, p) = (copy[0].as_str().unwrap_or_default(), copy[1].clone());
|
||||
run(&mut s, id, p);
|
||||
let names = run(&mut s, "inspect.measure", json!({}))["bodies"].as_array().map(|b| b.iter().map(|x| x["name"].clone()).collect::<Vec<_>>());
|
||||
assert_eq!(names, Some(vec![json!("rim")]), "{id}: one body, the merged rim and hub");
|
||||
// Every copy adds what the seed spoke added (curved bodies measure to about 0.02 %; a
|
||||
// missing or doubled spoke is about 5 %).
|
||||
assert!(rel(volume(&mut s), v0 + n * (v1 - v0)) < 1e-3, "{id}: {} vs {}", volume(&mut s), v0 + n * (v1 - v0));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1864,11 +1864,8 @@ fn c_symmetry(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cb = sk.curve_index(rb).ok_or_else(|| bad(cmd, format!("unknown entity `{rb}`")))?;
|
||||
match (sk.curves.get(ca).map(|c| c.kind.clone()), sk.curves.get(cb).map(|c| c.kind.clone())) {
|
||||
(Some(CurveKind::Line { a: a0, b: a1 }), Some(CurveKind::Line { a: b0, b: b1 })) => {
|
||||
// Opposite sides of a rectangle run in opposite directions: pair each end
|
||||
// with the end of the other line nearest its mirror image (#2961, #2940).
|
||||
let (p0, p1) = if mirror_pairing_is_crossed(sk, l, [a0, a1], [b0, b1]) { (b1, b0) } else { (b0, b1) };
|
||||
out.push(add_c(sk, ConstraintKind::Symmetric { p: a0, q: p0, l })?);
|
||||
out.push(add_c(sk, ConstraintKind::Symmetric { p: a1, q: p1, l })?);
|
||||
out.push(add_c(sk, ConstraintKind::Symmetric { p: a0, q: b0, l })?);
|
||||
out.push(add_c(sk, ConstraintKind::Symmetric { p: a1, q: b1, l })?);
|
||||
}
|
||||
(Some(_), Some(_)) => {
|
||||
let pa = round_center(sk, ca).ok_or_else(|| bad(cmd, "symmetry needs two lines or two circles/arcs"))?;
|
||||
@@ -1889,25 +1886,6 @@ fn c_symmetry(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"constraints": ids, "sketch": info}))
|
||||
}
|
||||
|
||||
/// True when the ends of line `a` mirror (about the line `l`) closer onto the ends of `b` crossed
|
||||
/// (`a0` with `b1`, `a1` with `b0`) than in order. A degenerate symmetry line keeps the order.
|
||||
fn mirror_pairing_is_crossed(sk: &Sketch, l: usize, a: [usize; 2], b: [usize; 2]) -> bool {
|
||||
let Some((o, e)) = line_pts(sk, l) else { return false };
|
||||
let d = e - o;
|
||||
let len2 = d.x * d.x + d.y * d.y;
|
||||
if len2 < 1e-18 {
|
||||
return false;
|
||||
}
|
||||
let pt = |i: usize| sk.point(i).unwrap_or_default();
|
||||
let near = |i: usize, j: usize| {
|
||||
let v = pt(i) - o;
|
||||
let t = (v.x * d.x + v.y * d.y) / len2;
|
||||
let foot = o + d * t;
|
||||
(foot * 2.0 - pt(i)).dist(pt(j))
|
||||
};
|
||||
near(a[0], b[1]) + near(a[1], b[0]) < near(a[0], b[0]) + near(a[1], b[1])
|
||||
}
|
||||
|
||||
/// Symmetry about point `c`: two points, two circles/arcs (their centres, and equal radii) or two
|
||||
/// lines (each end with the end of the other line nearest its mirror image). The constraints
|
||||
/// (the construction lines show in the response's `created`).
|
||||
@@ -2535,11 +2513,9 @@ fn move_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "sketch.move_point";
|
||||
let to = req_vec2(cmd, p, "to")?;
|
||||
let id = target_sketch(s, p, cmd)?;
|
||||
let state = s.model.result(id).map(|r| r.state.clone());
|
||||
let last = state.as_ref().and_then(|state| state.sketch(id));
|
||||
let (_, rep) = edit_solved(s, id, false, Analysis::Freedom, |sk, _| {
|
||||
let q = point_ref(sk, p.get("point"), cmd, "point")?;
|
||||
Ok(((), drag_entity(sk, Ent::Point(q), &[], to, to, false, last).1.solve_again()))
|
||||
Ok(((), drag_entity(sk, Ent::Point(q), &[], to, to, false).1.solve_again()))
|
||||
})?;
|
||||
Ok(json!({"sketch": rep.as_ref().map(report_json)}))
|
||||
}
|
||||
@@ -2562,8 +2538,7 @@ fn drag_frame(s: &mut Session, p: &Value, live: bool) -> Result<(Value, Option<c
|
||||
};
|
||||
let id = target_sketch(s, p, cmd)?;
|
||||
// The sketch's report as last evaluated: a live frame keeps its degrees of freedom.
|
||||
let state = s.model.result(id).map(|r| r.state.clone());
|
||||
let last = state.as_ref().and_then(|state| state.sketch(id));
|
||||
let last = s.model.result(id).and_then(|r| r.state.sketch(id)).map(|ss| ss.report.clone());
|
||||
let analysis = if live { Analysis::Full } else { Analysis::Freedom };
|
||||
let (d, rep) = edit_solved(s, id, false, analysis, |sk, doc| {
|
||||
let r = p.get("entity").and_then(Value::as_str).ok_or_else(|| bad(cmd, "`entity` must be a sketch point or curve"))?;
|
||||
@@ -2590,7 +2565,7 @@ fn drag_frame(s: &mut Session, p: &Value, live: bool) -> Result<(Value, Option<c
|
||||
}
|
||||
// The held solves work on the dimensions' current values (a solved step applies them).
|
||||
doc.apply_dimension_values(&doc.param_values().0, sk)?;
|
||||
let (d, left) = drag_entity(sk, e, &with, from, to, live, last);
|
||||
let (d, left) = drag_entity(sk, e, &with, from, to, live);
|
||||
// A live frame's held solve is its only one; otherwise the sketch's own solve reports
|
||||
// its degrees of freedom.
|
||||
Ok((d, if live && last.is_some() { left } else { left.solve_again() }))
|
||||
@@ -2599,7 +2574,7 @@ fn drag_frame(s: &mut Session, p: &Value, live: bool) -> Result<(Value, Option<c
|
||||
// average displacement of their moving points, as before.
|
||||
let sk = s.doc.sketch(id)?;
|
||||
let at = d.at(sk, from);
|
||||
let rep = rep.or_else(|| last.map(|ss| SolveReport { status: solidcraft_sketch::SolveStatus::Solved, failing: Vec::new(), ..ss.report.clone() }));
|
||||
let rep = rep.or_else(|| last.map(|last| SolveReport { status: solidcraft_sketch::SolveStatus::Solved, failing: Vec::new(), ..last }));
|
||||
let out = json!({"sketch": rep.as_ref().map(report_json), "reached": d.reached, "at": [at.x, at.y], "retry": d.retry});
|
||||
Ok((out, rep.filter(|_| live).map(|report| crate::LiveEdit { sketch: id, report })))
|
||||
}
|
||||
|
||||
@@ -374,66 +374,6 @@ fn symmetry_moves_a_free_line_between_two_fixed_lines() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A 20 x 10 rectangle (sides l1..l4; left = l4 and right = l2 run in opposite directions) and a
|
||||
/// free vertical line at x = -20 as the symmetry line (#2940, #2961).
|
||||
fn rectangle_and_axis(dimension_left: bool) -> (Session, Vec<String>) {
|
||||
let mut s = new_sketch();
|
||||
let r = run(&mut s, "sketch.rectangle.two_point", json!({"p0": [-12, 0], "p1": [8, 10]}));
|
||||
let sides = ids(&r["curves"]);
|
||||
run(&mut s, "sketch.line", json!({"points": [[-20, -5], [-20, 15]], "construction": true, "ids": ["axis"]}));
|
||||
if dimension_left {
|
||||
run(&mut s, "sketch.dimension", json!({"entities": [sides[3].clone()], "value": 10}));
|
||||
}
|
||||
(s, sides)
|
||||
}
|
||||
|
||||
/// Both sides keep their 10 mm height and their ends mirror in x about `axis_x`.
|
||||
fn assert_sides_mirror_with_height(s: &Session, left: &str, right: &str, axis_x: f64) {
|
||||
let sk = sketch(s);
|
||||
let at = |r: String| sk.point(sk.resolve_point(&r).unwrap()).unwrap();
|
||||
for side in [left, right] {
|
||||
let (a, b) = (at(format!("{side}.start")), at(format!("{side}.end")));
|
||||
assert!((a.y - b.y).abs() > 9.999 && (a.y - b.y).abs() < 10.001, "{side} height {:?} {:?}", a, b);
|
||||
assert!((a.x - b.x).abs() < 1e-7, "{side} not vertical: {:?} {:?}", a, b);
|
||||
}
|
||||
let (l, r) = (at(format!("{left}.start")), at(format!("{right}.start")));
|
||||
assert!((l.x + r.x - 2.0 * axis_x).abs() < 1e-6, "sides not mirrored: {l:?} {r:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symmetry_of_rectangle_sides_keeps_their_height() {
|
||||
// #2940: the opposite sides of a rectangle run in opposite directions, so pairing their ends
|
||||
// by index forced both heights to 0.
|
||||
let (mut s, sides) = rectangle_and_axis(false);
|
||||
run(&mut s, "sketch.constraint.symmetry", json!({"a": sides[3], "b": sides[1], "line": "axis"}));
|
||||
assert_sides_mirror_with_height(&s, &sides[3], &sides[1], -20.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symmetry_of_a_dimensioned_rectangle_side_is_accepted() {
|
||||
// #2961: with a length on a side, the same symmetry was refused as "neither entity can move".
|
||||
let (mut s, sides) = rectangle_and_axis(true);
|
||||
run(&mut s, "sketch.constraint.symmetry", json!({"a": sides[3], "b": sides[1], "line": "axis"}));
|
||||
assert_sides_mirror_with_height(&s, &sides[3], &sides[1], -20.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symmetry_of_rectangle_sides_with_swapped_arguments() {
|
||||
let (mut s, sides) = rectangle_and_axis(true);
|
||||
run(&mut s, "sketch.constraint.symmetry", json!({"a": sides[1], "b": sides[3], "line": "axis"}));
|
||||
assert_sides_mirror_with_height(&s, &sides[3], &sides[1], -20.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symmetry_of_rectangle_sides_about_the_y_axis() {
|
||||
let mut s = new_sketch();
|
||||
let r = run(&mut s, "sketch.rectangle.two_point", json!({"p0": [-12, 0], "p1": [8, 10]}));
|
||||
let sides = ids(&r["curves"]);
|
||||
run(&mut s, "sketch.dimension", json!({"entities": [sides[3].clone()], "value": 10}));
|
||||
run(&mut s, "sketch.constraint.symmetry", json!({"a": sides[3], "b": sides[1], "line": "y"}));
|
||||
assert_sides_mirror_with_height(&s, &sides[3], &sides[1], 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn midpoint_alignment_persists_undoes_and_survives_endpoint_edits() {
|
||||
use solidcraft_sketch::ConstraintKind;
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use solidcraft_geom::Vec2;
|
||||
use solidcraft_sketch::{ConstraintKind, CurveKind, LinkKind, LinkSource, Shape, Sketch, TextAlign, TextExprs, TextStyle};
|
||||
use solidcraft_sketch::{ConstraintKind, CurveKind, LinkKind, LinkSource, Sketch, TextAlign, TextExprs, TextStyle};
|
||||
|
||||
/// The style parameters of `sketch.text` and `sketch.edit_text`.
|
||||
macro_rules! text_style_doc {
|
||||
@@ -822,39 +822,6 @@ fn guess_radius(sk: &Sketch, curves: &[usize], at: Vec2) -> f64 {
|
||||
if r.is_finite() && r > 1e-6 { r } else { 1.0 }
|
||||
}
|
||||
|
||||
/// Where the centre of a circle of radius `d` touching `sh` can lie: the line moved `d` to either
|
||||
/// side, or the circle grown and shrunk by `d` (arcs as their full circle).
|
||||
fn centre_paths(sh: &Shape, d: f64) -> Vec<Shape> {
|
||||
match *sh {
|
||||
Shape::Line { a, b } => {
|
||||
(b - a).normalized().map(|u| [d, -d].map(|s| Shape::Line { a: a + u.perp() * s, b: b + u.perp() * s }).to_vec()).unwrap_or_default()
|
||||
}
|
||||
Shape::Round { c, r, .. } => [r + d, (r - d).abs()]
|
||||
.into_iter()
|
||||
.filter(|x| *x > 1e-12)
|
||||
.map(|r| Shape::Round { c, r, start: 0.0, sweep: std::f64::consts::TAU })
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The centre nearest `near` of a circle of radius `r` touching curves `a` and `b` (#3141): the
|
||||
/// solver starts from the answer instead of from the click, which lies on a curve, where the
|
||||
/// tangency has no side yet and the solve fails or moves the curves.
|
||||
fn tangent_centre(sk: &Sketch, a: usize, b: usize, r: f64, near: Vec2) -> Option<Vec2> {
|
||||
let (sa, sb) = (sk.shape(a)?, sk.shape(b)?);
|
||||
let mut best: Option<Vec2> = None;
|
||||
for x in centre_paths(&sa, r) {
|
||||
for y in centre_paths(&sb, r) {
|
||||
for q in solidcraft_sketch::intersections_within(&x, &y, 1e-9 * (1.0 + r)) {
|
||||
if q.x.is_finite() && q.y.is_finite() && best.is_none_or(|b| q.dist(near) < b.dist(near)) {
|
||||
best = Some(q);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
fn tangent_curves(sk: &Sketch, p: &Value, cmd: &str, n: usize) -> Result<Vec<usize>> {
|
||||
let ids = string_list(p, "curves");
|
||||
if ids.len() != n {
|
||||
@@ -875,14 +842,10 @@ fn tangent_circle(s: &mut Session, p: &Value, cmd: &str, n: usize, radius: Optio
|
||||
if !(r0 > 1e-9 && r0 < 1e8) {
|
||||
return Err(bad(cmd, "radius must be positive"));
|
||||
}
|
||||
// Start where the circle already touches when that can be worked out (two curves and a
|
||||
// radius), so that only the new circle moves.
|
||||
let start = match cs.as_slice() {
|
||||
[a, b] if radius.is_some() => tangent_centre(sk, *a, *b, r0, near).unwrap_or(near),
|
||||
_ => near,
|
||||
};
|
||||
// Start where the circle already nearly touches: move the centre so the guessed circle
|
||||
// sits between the curves.
|
||||
let first_new = sk.points.len();
|
||||
let c = sk.add_circle(start, r0, None, None)?;
|
||||
let c = sk.add_circle(near, r0, None, None)?;
|
||||
let mut cons = Vec::new();
|
||||
for k in &cs {
|
||||
cons.push(add_c(sk, ConstraintKind::Tangent { a: *k, b: c })?);
|
||||
|
||||
@@ -125,33 +125,7 @@ impl Path {
|
||||
///
|
||||
/// `live`: one frame of an interactive drag, whose held solves and cursor correction share
|
||||
/// one frame's work budget ([`Budget::frame`]); otherwise each has a solve's own.
|
||||
///
|
||||
/// `solved`: the sketch as last evaluated. When it is unchanged and solved, a grabbed entity it
|
||||
/// determined is not dragged.
|
||||
pub(super) fn drag_entity(
|
||||
sk: &mut Sketch,
|
||||
e: Ent,
|
||||
with: &[Ent],
|
||||
from: Vec2,
|
||||
to: Vec2,
|
||||
live: bool,
|
||||
solved: Option<&solidcraft_doc::SolvedSketch>,
|
||||
) -> (Dragged, Left) {
|
||||
// An unchanged, solved entity with no freedom cannot follow a drag. Holding it at a
|
||||
// different position only makes its constraints conflict, and a large pattern would spend
|
||||
// minutes trying dense solves before returning to the same geometry (#2006).
|
||||
if solved.is_some_and(|ss| {
|
||||
ss.report.ok()
|
||||
&& ss.sketch == *sk
|
||||
&& match e {
|
||||
Ent::Point(q) => ss.report.point_determined.get(q),
|
||||
Ent::Curve(c) => ss.report.curve_determined.get(c),
|
||||
}
|
||||
.copied()
|
||||
.unwrap_or(false)
|
||||
}) {
|
||||
return (Dragged::default(), Left::Solved);
|
||||
}
|
||||
pub(super) fn drag_entity(sk: &mut Sketch, e: Ent, with: &[Ent], from: Vec2, to: Vec2, live: bool) -> (Dragged, Left) {
|
||||
let Some((path, hold, n, short)) = prepare(sk, e, with, from, to) else {
|
||||
return (Dragged::default(), Left::Unsolved);
|
||||
};
|
||||
|
||||
@@ -7,52 +7,6 @@ use solidcraft_geom::Vec3;
|
||||
use super::solve_counts;
|
||||
use crate::Session;
|
||||
|
||||
#[test]
|
||||
fn determined_pattern_geometry_does_not_attempt_conflicting_held_solves() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY"}));
|
||||
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [5, 5], "p1": [6.5, 6.5]}));
|
||||
run(&mut s, "sketch.dimension", json!({"entities": ["l1"], "value": 1.5}));
|
||||
run(&mut s, "sketch.dimension", json!({"entities": ["l2"], "value": 1.5}));
|
||||
run(&mut s, "sketch.constraint.fix", json!({"entities": ["l1.start"]}));
|
||||
let pattern = run(
|
||||
&mut s,
|
||||
"sketch.pattern.rectangular",
|
||||
json!({"entities": ["l1", "l2", "l3", "l4"], "count": 3, "count2": 3, "spacing": 2.2, "spacing2": -2.2}),
|
||||
);
|
||||
let line = pattern["curves"][0].as_str().expect("a patterned line");
|
||||
let endpoint = format!("{line}.start");
|
||||
let before = sketch_of(&s);
|
||||
assert!(!before.curve_locked(before.curve_index(line).expect("patterned line index")));
|
||||
for entity in [line, endpoint.as_str()] {
|
||||
for live in [true, false] {
|
||||
reset(&mut s);
|
||||
let result = run(&mut s, "sketch.drag", json!({"entity": entity, "from": [5, 5], "to": [9, 12], "live": live}));
|
||||
assert_eq!(result["reached"], json!(0.0));
|
||||
assert_eq!(result["at"], json!([5.0, 5.0]));
|
||||
assert_eq!(result["sketch"]["solved"], json!(true));
|
||||
let full = usize::from(!live);
|
||||
assert_eq!(solve_counts::take(), (full, full), "no held solve for determined geometry");
|
||||
assert_eq!(sketch_of(&s), before);
|
||||
}
|
||||
}
|
||||
reset(&mut s);
|
||||
run(&mut s, "sketch.move_point", json!({"point": endpoint, "to": [9, 12]}));
|
||||
assert_eq!(solve_counts::take(), (1, 1), "move_point also skips held solves");
|
||||
assert_eq!(sketch_of(&s), before);
|
||||
|
||||
// A cached determined report must not suppress an outstanding dimension edit.
|
||||
let dimension = before
|
||||
.constraints
|
||||
.iter()
|
||||
.find(|c| matches!(c.kind, solidcraft_sketch::ConstraintKind::Length { l: 0, .. }))
|
||||
.and_then(|c| c.param.as_ref())
|
||||
.expect("the first line's dimension");
|
||||
s.doc_mut().params.iter_mut().find(|p| &p.name == dimension).expect("dimension parameter").expr = "3".into();
|
||||
run(&mut s, "sketch.drag", json!({"entity": line, "from": [5, 5], "to": [9, 12], "live": true}));
|
||||
assert!((pt(&s, "l1.start").dist(pt(&s, "l1.end")) - 3.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
match s.execute(id, &p) {
|
||||
Ok(v) => v,
|
||||
|
||||
@@ -438,51 +438,6 @@ fn new_creation_tools() {
|
||||
assert!(a.iter().any(|x| close(*x, pi * 5.0 * 2.0 + pi)), "{a:?}");
|
||||
}
|
||||
|
||||
/// #3141: a 2-tangent circle asked for near a point on one of its curves (where a click on that
|
||||
/// curve puts it) is solved from the touching circle nearest that point: it lands in the corner,
|
||||
/// the rectangle stays as drawn, and fixed sides no longer make it fail.
|
||||
#[test]
|
||||
fn two_tangent_circle_from_a_click_on_a_curve_leaves_the_curves_as_drawn() {
|
||||
let side = |s: &Session, sides: &[String], on: fn(Vec2) -> bool| -> String {
|
||||
let sk = sketch(s);
|
||||
sides
|
||||
.iter()
|
||||
.find(|c| {
|
||||
let i = sk.curve_index(c).unwrap();
|
||||
matches!(sk.shape(i), Some(solidcraft_sketch::Shape::Line { a, b }) if on(a) && on(b))
|
||||
})
|
||||
.unwrap()
|
||||
.clone()
|
||||
};
|
||||
let points = |s: &Session| sketch(s).points.iter().map(|p| p.pos).collect::<Vec<_>>();
|
||||
for fixed in [false, true] {
|
||||
let mut s = new_sketch();
|
||||
let r = run(&mut s, "sketch.rectangle.two_point", json!({"p0": [-800, 0], "p1": [-300, 500]}));
|
||||
let sides = ids(&r["curves"]);
|
||||
if fixed {
|
||||
run(&mut s, "sketch.constraint.fix", json!({"entities": sides}));
|
||||
}
|
||||
let before = points(&s);
|
||||
let bottom = side(&s, &sides, |p| p.y.abs() < 1e-9);
|
||||
let left = side(&s, &sides, |p| (p.x + 800.0).abs() < 1e-9);
|
||||
// Midway between a click on the bottom side and one on the left side.
|
||||
let r = run(&mut s, "sketch.circle.two_tangent", json!({"curves": [bottom, left], "radius": 50, "near": [-675, 125]}));
|
||||
let c = ids(&r["curves"])[0].clone();
|
||||
let sk = sketch(&s);
|
||||
let ci = sk.curve_index(&c).unwrap();
|
||||
assert!(sk.center(ci).unwrap().dist(Vec2::new(-750.0, 50.0)) < 1e-6, "fixed {fixed}: {:?}", sk.center(ci));
|
||||
assert!(close(sk.radius(ci).unwrap(), 50.0));
|
||||
let after = points(&s);
|
||||
assert!(before.iter().zip(&after).all(|(a, b)| a.dist(*b) < 1e-9), "fixed {fixed}: the rectangle did not move: {after:?}");
|
||||
// Asked for right on the left side: still a touching circle next to it.
|
||||
let r = run(&mut s, "sketch.circle.two_tangent", json!({"curves": [bottom, left], "radius": 20, "near": [-800, 30]}));
|
||||
let c = ids(&r["curves"])[0].clone();
|
||||
let sk = sketch(&s);
|
||||
let o = sk.center(sk.curve_index(&c).unwrap()).unwrap();
|
||||
assert!(close(o.y, 20.0) && close((o.x + 800.0).abs(), 20.0), "fixed {fixed}: {o:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ellipse_splines_conic() {
|
||||
let pi = std::f64::consts::PI;
|
||||
|
||||
@@ -431,24 +431,16 @@ impl Session {
|
||||
|
||||
/// Become `fresh` (another design opened, recovered or started), keeping the settings that
|
||||
/// are the user's rather than the design's: `auto_project` is a preference (#680).
|
||||
/// Checkpoints survive too: a batch that failed after `file.new` or `doc.open` goes back
|
||||
/// from the checkpoint it took before its first step, and that checkpoint belongs to the
|
||||
/// design before the batch, which is what the batch promised (#3242). The design is what a
|
||||
/// checkpoint keeps, not the replaced session's file path (docs/mcp.md).
|
||||
pub fn replace_design(&mut self, fresh: Session) {
|
||||
let auto_project = self.auto_project;
|
||||
let param_check = self.param_check;
|
||||
let render_viewport = self.render_viewport.clone();
|
||||
let render_jobs = self.render_jobs.scratch();
|
||||
let checkpoints = std::mem::take(&mut self.checkpoints);
|
||||
let next_checkpoint = self.next_checkpoint;
|
||||
*self = fresh;
|
||||
self.auto_project = auto_project;
|
||||
self.param_check = param_check;
|
||||
self.render_viewport = render_viewport;
|
||||
self.render_jobs = render_jobs;
|
||||
self.checkpoints = checkpoints;
|
||||
self.next_checkpoint = next_checkpoint;
|
||||
}
|
||||
|
||||
/// The design has changes not in its file: in the document, or in what is hidden.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Autosave and crash recovery.
|
||||
//!
|
||||
//! Each open design keeps its own recovery entry in the recovery folder: `<id>.solidcraft` (the design
|
||||
//! A running app keeps one recovery entry in the recovery folder: `<id>.solidcraft` (the design
|
||||
//! as of the last autosave), `<id>.json` (its file path, name and time) and `<id>.lock`, which
|
||||
//! the app holds locked while it runs. Autosaves are written atomically, only when the design
|
||||
//! has unsaved changes it hasn't written yet; a design with nothing unsaved has no entry. An
|
||||
@@ -163,7 +163,7 @@ pub fn remove(dir: &Path, id: &str) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One open design's autosaver. Keep it with that design when switching tabs.
|
||||
/// One app's autosaver.
|
||||
pub struct Autosaver {
|
||||
pub dir: PathBuf,
|
||||
pub id: String,
|
||||
@@ -232,7 +232,7 @@ impl Snapshot {
|
||||
}
|
||||
|
||||
impl Autosaver {
|
||||
/// Start autosaving into `dir` (created if needed), holding this design's lock.
|
||||
/// Start autosaving into `dir` (created if needed), holding this app's lock.
|
||||
pub fn new(dir: &Path, interval: Duration) -> Result<Autosaver> {
|
||||
let io = |e: std::io::Error| EngineError::Other(format!("{}: {e}", dir.display()));
|
||||
fs::create_dir_all(dir).map_err(io)?;
|
||||
@@ -361,20 +361,6 @@ impl Autosaver {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The user closed this design (saving it or choosing Don't Save): discard only its entry.
|
||||
pub fn discard(mut self) {
|
||||
// A write still running would recreate the entry, without a lock, after it is removed:
|
||||
// the next launch would offer a design the user closed.
|
||||
if let Some(w) = self.writing.take() {
|
||||
let _ = w.done.recv();
|
||||
}
|
||||
for ext in ["json", solidcraft_io::DESIGN_EXT] {
|
||||
let _ = fs::remove_file(file(&self.dir, &self.id, ext));
|
||||
}
|
||||
self.lock = None;
|
||||
let _ = fs::remove_file(file(&self.dir, &self.id, "lock"));
|
||||
}
|
||||
|
||||
/// Closing the app: with nothing unsaved the entry goes; otherwise it stays for the next
|
||||
/// launch to offer. The lock is released either way.
|
||||
pub fn close(mut self, s: &Session) {
|
||||
|
||||
@@ -1785,23 +1785,6 @@ fn checkpoint_restores_with_a_full_undo_history() {
|
||||
assert!(s.execute("edit.restore_checkpoint", &json!({"checkpoint": id})).is_err());
|
||||
}
|
||||
|
||||
/// Regression (#3242): `file.new` replaced the session and its checkpoints with it, so a
|
||||
/// batch that failed after `file.new` could not go back to the design it began in.
|
||||
#[test]
|
||||
fn a_checkpoint_survives_file_new() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.box", json!({"length": 1.0, "width": 1.0, "height": 1.0}));
|
||||
let id = run(&mut s, "edit.checkpoint", json!({}))["checkpoint"].as_u64().unwrap();
|
||||
run(&mut s, "file.new", json!({"name": "Replacement"}));
|
||||
run(&mut s, "solid.box", json!({"length": 2.0, "width": 2.0, "height": 2.0}));
|
||||
assert_eq!(run(&mut s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64(), Some(8.0));
|
||||
run(&mut s, "edit.restore_checkpoint", json!({"checkpoint": id}));
|
||||
assert_eq!(run(&mut s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64(), Some(1.0));
|
||||
// The undo history is the restored design's own: one step back is the empty design.
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(run(&mut s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64(), Some(0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn components_occurrences_and_world_placement() {
|
||||
let mut s = Session::default();
|
||||
|
||||
@@ -170,8 +170,8 @@ fn wrong_up_and_names_are_refused() {
|
||||
assert_eq!(kinds(&s), ["BoxFeature", "BaseFeature"]);
|
||||
}
|
||||
|
||||
/// Explicit naming choices select the solid, part or occurrence; automatic naming keeps
|
||||
/// meaningful solid names.
|
||||
/// `names` says what the bodies are called: the solid's own name (the default), the part's, or
|
||||
/// the assembly occurrence's. Repeated names are numbered as ever.
|
||||
#[test]
|
||||
fn the_bodies_are_named_after_the_solid_the_product_or_the_instance() {
|
||||
let path = frame_file("names");
|
||||
@@ -185,7 +185,6 @@ fn the_bodies_are_named_after_the_solid_the_product_or_the_instance() {
|
||||
// The post is placed twice: one component, two occurrences, its body built once (#1386).
|
||||
let solids = ["Cut-Extrude3", "Boss-Extrude1"];
|
||||
assert_eq!(named(json!({"path": path})), solids);
|
||||
assert_eq!(named(json!({"path": path, "names": "auto"})), solids);
|
||||
assert_eq!(named(json!({"path": path, "names": "solid"})), solids);
|
||||
assert_eq!(named(json!({"path": path, "names": "product"})), ["Plate", "Post"]);
|
||||
assert_eq!(named(json!({"path": path, "names": "Instance"})), ["Plate-1", "Post-1"]);
|
||||
@@ -229,29 +228,3 @@ fn a_step_file_can_be_inserted_at_a_matrix() {
|
||||
assert!(e.contains("not rigid"), "{e}");
|
||||
assert!(d.doc.features.is_empty() && d.doc.occurrences.is_empty());
|
||||
}
|
||||
|
||||
/// Generated body labels become part names, and the saved assembly retains its components
|
||||
/// and repeated placements without needing the source file.
|
||||
#[test]
|
||||
fn automatic_part_names_and_assembly_survive_reopening() {
|
||||
let path = frame_file("automatic");
|
||||
let text = std::fs::read_to_string(&path).unwrap().replace("'Cut-Extrude3'", "'Body1'").replace("'Boss-Extrude1'", "'Body 2 (3)'");
|
||||
std::fs::write(&path, text).unwrap();
|
||||
let mut s = Session::default();
|
||||
let r = run(&mut s, "file.insert_step", json!({"path": path}));
|
||||
assert_eq!(body_names(&s), ["Plate", "Post"]);
|
||||
let top = r["component"].as_u64().unwrap();
|
||||
let parts: Vec<_> = s.doc.components.iter().filter(|c| c.parent == top).collect();
|
||||
assert_eq!(parts.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["Plate", "Post"]);
|
||||
assert_eq!(s.doc.occurrences.iter().filter(|o| o.component == parts[1].id && o.parent == top).count(), 2);
|
||||
let design = std::path::Path::new(&path).with_file_name("automatic.solidcraft");
|
||||
run(&mut s, "file.save_as", json!({"path": design.to_string_lossy()}));
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
let mut again = Session::default();
|
||||
run(&mut again, "doc.open", json!({"path": design.to_string_lossy()}));
|
||||
assert_eq!(body_names(&again), ["Plate", "Post"]);
|
||||
assert_eq!(again.doc.components, s.doc.components);
|
||||
assert_eq!(again.doc.occurrences, s.doc.occurrences);
|
||||
assert!(near(extent(&again).0, [0.0, 0.0, 0.0]) && near(extent(&again).1, [40.0, 34.0, 20.0]));
|
||||
assert!((total_volume(&mut again) - (40.0 * 4.0 * 20.0 + 2.0 * 4.0 * 30.0 * 4.0)).abs() < 1e-6);
|
||||
}
|
||||
|
||||
+12
-31
@@ -101,10 +101,8 @@ pub fn is_iges_path(path: &str) -> bool {
|
||||
/// nothing), so the caller chooses.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum StepNames {
|
||||
/// Keep meaningful solid names; replace placeholders with the nearest named product.
|
||||
#[default]
|
||||
Auto,
|
||||
/// The solid's own name in the file, else the name of the product that holds it.
|
||||
#[default]
|
||||
Solid,
|
||||
/// The name of the product (part) that holds the body, else the solid's name.
|
||||
Product,
|
||||
@@ -114,10 +112,9 @@ pub enum StepNames {
|
||||
}
|
||||
|
||||
impl StepNames {
|
||||
/// `auto`, `solid`, `product` or `instance` (any case); `None` for anything else.
|
||||
/// `solid`, `product` or `instance` (any case); `None` for anything else.
|
||||
pub fn parse(s: &str) -> Option<StepNames> {
|
||||
match s.trim().to_ascii_lowercase().as_str() {
|
||||
"auto" => Some(StepNames::Auto),
|
||||
"solid" => Some(StepNames::Solid),
|
||||
"product" => Some(StepNames::Product),
|
||||
"instance" => Some(StepNames::Instance),
|
||||
@@ -129,16 +126,7 @@ impl StepNames {
|
||||
/// A name that says nothing about its body: empty, or the placeholder a file or the importer
|
||||
/// gives to something it has no name for.
|
||||
fn generic_name(n: &str) -> bool {
|
||||
let n = n.trim();
|
||||
n.is_empty()
|
||||
|| n.starts_with('(')
|
||||
|| n.eq_ignore_ascii_case("import")
|
||||
|| n.eq_ignore_ascii_case("unnamed")
|
||||
|| ["body", "solid", "shell"].iter().any(|prefix| {
|
||||
n.get(..prefix.len()).is_some_and(|s| s.eq_ignore_ascii_case(prefix))
|
||||
&& n.get(prefix.len()..)
|
||||
.is_some_and(|s| s.chars().all(|c| c.is_ascii_digit() || c.is_ascii_whitespace() || matches!(c, '_' | '-' | '(' | ')')))
|
||||
})
|
||||
n.trim().is_empty() || n.starts_with('(') || n.eq_ignore_ascii_case("import") || n.eq_ignore_ascii_case("unnamed")
|
||||
}
|
||||
|
||||
/// The name an imported body gets under the `names` choice; the solid's name when the chosen
|
||||
@@ -146,8 +134,6 @@ fn generic_name(n: &str) -> bool {
|
||||
fn body_name(b: &solidcraft_kernel::ImportedBody, names: StepNames) -> String {
|
||||
let usable = |n: &&String| !generic_name(n);
|
||||
let chosen = match names {
|
||||
StepNames::Auto if !generic_name(&b.name) => Some(&b.name),
|
||||
StepNames::Auto => b.path.iter().rev().find(usable).or_else(|| b.instance.as_ref().filter(usable)),
|
||||
StepNames::Solid => None,
|
||||
StepNames::Product => b.path.last().filter(usable),
|
||||
StepNames::Instance => b.instance.as_ref().filter(usable).or(b.path.last().filter(usable)),
|
||||
@@ -160,7 +146,8 @@ pub struct StepFeature {
|
||||
/// Timeline name: the root product's name, else the file name.
|
||||
pub name: String,
|
||||
pub kind: solidcraft_doc::FeatureKind,
|
||||
/// Body names from the file, as [`StepNames`] chose them (automatic by default).
|
||||
/// Body names from the file, as [`StepNames`] chose them (by default the solid names, else
|
||||
/// the product names).
|
||||
pub body_names: Vec<String>,
|
||||
pub warnings: Vec<String>,
|
||||
/// The file as read. Hold it until the feature has been evaluated: the timeline then reuses
|
||||
@@ -761,7 +748,7 @@ mod tests {
|
||||
let step = String::from_utf8(export_with_metadata(&m.state(), &[], Format::Step, "t", &meta).unwrap()).unwrap();
|
||||
assert!(step.contains("FILE_DESCRIPTION(('Vented Geh\\X2\\00E4\\X0\\use for a Pi'),'2;1');"), "{}", &step[..300]);
|
||||
assert!(step.contains("FILE_NAME('t.step','',('Jane O''Brien'),('ACME'),"), "{}", &step[..300]);
|
||||
assert_eq!(step_import_feature(step.as_bytes(), "t.step").unwrap().body_names, ["t"], "still reads back");
|
||||
assert_eq!(step_import_feature(step.as_bytes(), "t.step").unwrap().body_names, ["Body1"], "still reads back");
|
||||
let iges = String::from_utf8(export_with_metadata(&m.state(), &[], Format::Iges, "t", &meta).unwrap()).unwrap();
|
||||
assert!(iges.contains("12HJane O'Brien") && iges.contains("4HACME"));
|
||||
let model_xml = |bytes: Vec<u8>| {
|
||||
@@ -825,7 +812,7 @@ mod tests {
|
||||
let f = step_import_feature(s.as_bytes(), "/tmp/My Part.step").unwrap();
|
||||
// Named after the exported product (the export was called `t`).
|
||||
assert_eq!(f.name, "t");
|
||||
assert_eq!(f.body_names, ["t"]);
|
||||
assert_eq!(f.body_names, ["Body1"]);
|
||||
assert_eq!(f.body_names.len(), 1);
|
||||
assert!(matches!(&f.kind, FeatureKind::Import { file, .. } if file == "My Part.step"));
|
||||
let mut imported = Document::new("Imported STEP round trip");
|
||||
@@ -875,8 +862,9 @@ mod tests {
|
||||
step_export_products(&products, 0, &StepHeader::default()).unwrap()
|
||||
}
|
||||
|
||||
/// Automatic names keep meaningful solid labels and replace placeholders with part names.
|
||||
/// Explicit choices still select the solid, product or occurrence.
|
||||
/// The bodies of a STEP file are named after the solid (the default), the product that holds
|
||||
/// them, or the assembly occurrence; a name the file leaves out or fills with a placeholder
|
||||
/// falls back to the next one.
|
||||
#[test]
|
||||
fn step_import_names_follow_the_choice() {
|
||||
let text = frame_step();
|
||||
@@ -884,15 +872,10 @@ mod tests {
|
||||
assert_eq!(names(&text, StepNames::Solid), ["Cut-Extrude3", "Boss-Extrude1", "Boss-Extrude1"]);
|
||||
assert_eq!(names(&text, StepNames::Product), ["Plate", "Post", "Post"]);
|
||||
assert_eq!(names(&text, StepNames::Instance), ["Plate-1", "Post-1", "Post-2"]);
|
||||
// Meaningful solid names survive automatic naming, including SolidCraft exports.
|
||||
// Without a choice it is the solid's name, as before.
|
||||
assert_eq!(step_import_feature(text.as_bytes(), "frame.step").unwrap().body_names, names(&text, StepNames::Solid));
|
||||
let generic = text.replace("'Cut-Extrude3'", "'Body1'").replace("'Boss-Extrude1'", "'Body 2 (3)'");
|
||||
assert_eq!(step_import_feature(generic.as_bytes(), "frame.step").unwrap().body_names, ["Plate", "Post", "Post"]);
|
||||
assert_eq!(names(&generic, StepNames::Solid), ["Body1", "Body 2 (3)", "Body 2 (3)"]);
|
||||
let named = generic.replace("'Body1'", "'Body housing'");
|
||||
assert_eq!(names(&named, StepNames::Auto), ["Body housing", "Post", "Post"]);
|
||||
// The timeline entry is the root product's name whatever the bodies are called.
|
||||
for choice in [StepNames::Auto, StepNames::Solid, StepNames::Product, StepNames::Instance] {
|
||||
for choice in [StepNames::Solid, StepNames::Product, StepNames::Instance] {
|
||||
assert_eq!(step_import_feature_named(text.as_bytes(), "frame.step", choice).unwrap().name, "Frame");
|
||||
}
|
||||
// A product the file leaves unnamed says nothing: its bodies keep the solid's name.
|
||||
@@ -904,8 +887,6 @@ mod tests {
|
||||
assert_eq!(names(&part, StepNames::Solid), ["Body1"]);
|
||||
assert_eq!(names(&part, StepNames::Product), ["Bracket"]);
|
||||
assert_eq!(names(&part, StepNames::Instance), ["Bracket"]);
|
||||
assert_eq!(names(&part, StepNames::Auto), ["Bracket"]);
|
||||
assert_eq!(StepNames::parse(" AuTo "), Some(StepNames::Auto));
|
||||
assert_eq!(StepNames::parse(" Product "), Some(StepNames::Product));
|
||||
assert_eq!(StepNames::parse("INSTANCE"), Some(StepNames::Instance));
|
||||
assert_eq!(StepNames::parse("label"), None);
|
||||
|
||||
@@ -541,17 +541,6 @@ thread_local! {
|
||||
pub(crate) static REPHASED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The volume one closed shell encloses, signed by the way its faces face (positive when they
|
||||
/// face out of it), from a mesh as coarse as the orientation mesh of a solid of its size.
|
||||
/// `None` when it cannot be meshed.
|
||||
pub(crate) fn shell_volume(shell: &mt::Shell) -> Option<f64> {
|
||||
let bounds: Aabb3 = shell.vertex_iter().map(|v| from_p3(v.point())).collect();
|
||||
let span = if bounds.is_empty() { 1.0 } else { bounds.diagonal() };
|
||||
let deflection = Deflection { display: true, ..Deflection::chord(orientation_tolerance(span)) };
|
||||
let v = guard("shell volume", || Ok(shell.robust_triangulation_within(deflection).to_polygon().volume())).ok()?;
|
||||
v.is_finite().then_some(v)
|
||||
}
|
||||
|
||||
/// Deflection the orientation mesh uses: coarse enough for a large solid, fine enough that a
|
||||
/// small one still tessellates. `unmeshed_faces` counts at the same value, so the count the
|
||||
/// orientation mesh produced is reused instead of meshing the body again.
|
||||
|
||||
+12
-47
@@ -1986,19 +1986,6 @@ fn loft_reversed(sections: &[(Plane, Loop2)]) -> Result<bool> {
|
||||
}
|
||||
|
||||
fn loft_numbered_wires(sections: &[(Plane, NumberedLoop)], reversed: bool) -> Result<(Vec<mt::Wire>, Vec<Vec<Vec<usize>>>)> {
|
||||
let mut wires: Vec<mt::Wire> = Vec::new();
|
||||
// Per section, the profile segments under each of its wire's edges.
|
||||
let mut edge_sources: Vec<Vec<Vec<usize>>> = Vec::new();
|
||||
for (p, r) in loft_section_loops(sections, reversed)? {
|
||||
wires.push(uniform_wire(&p, &r.lp)?);
|
||||
edge_sources.push(r.from);
|
||||
}
|
||||
Ok((wires, edge_sources))
|
||||
}
|
||||
|
||||
/// The sections of a loft as the wires are built from them: in loft order, oriented alike,
|
||||
/// re-split to the same number of segments and started where they line up best.
|
||||
pub(crate) fn loft_section_loops(sections: &[(Plane, NumberedLoop)], reversed: bool) -> Result<Vec<(Plane, NumberedLoop)>> {
|
||||
let n = sections.iter().map(|(_, l)| l.lp.segs.len()).max().unwrap_or(0);
|
||||
if n == 0 || n > MAX_SEGS {
|
||||
return Err(KernelError::Invalid("empty section".into()));
|
||||
@@ -2013,51 +2000,28 @@ pub(crate) fn loft_section_loops(sections: &[(Plane, NumberedLoop)], reversed: b
|
||||
// with the most segments.
|
||||
let n0 = ordered.first().map(|(p, _)| p.normal()).unwrap_or(Vec3::Z);
|
||||
let parallel = ordered.iter().all(|(p, _)| p.normal().dot(n0).abs() > 1.0 - 1e-9);
|
||||
// Whether a section faces the first one's way is followed neighbour to neighbour, not by its
|
||||
// normal against the first's: planes turning about an axis pass 90 degrees and would be
|
||||
// flipped, folding the loft (#2847).
|
||||
let mut facing = true;
|
||||
let mut before = n0;
|
||||
let oriented: Vec<(Plane, NumberedLoop)> = ordered
|
||||
.iter()
|
||||
.map(|(p, l)| {
|
||||
let n = p.normal();
|
||||
if n.dot(before) < 0.0 {
|
||||
facing = !facing;
|
||||
}
|
||||
before = n;
|
||||
(*p, l.oriented(!facing))
|
||||
let ccw = p.normal().dot(n0) >= 0.0;
|
||||
(*p, l.oriented(!ccw))
|
||||
})
|
||||
.collect();
|
||||
let lead = oriented.iter().max_by_key(|(_, l)| l.lp.segs.len()).ok_or_else(|| KernelError::Invalid("no sections".into()))?;
|
||||
let lead_c = lead.0.to_world(lead.1.lp.centroid());
|
||||
let lead_dirs: Vec<Vec3> = lead.1.lp.segs.iter().map(|s| lead.0.to_world(s.start()) - lead_c).collect();
|
||||
// The share of the lead's perimeter before each of its vertices: where a circle section
|
||||
// breaks when the lead's vertex directions do not go round in order.
|
||||
let lead_len: f64 = lead.1.lp.segs.iter().map(Seg2::length).sum();
|
||||
let fractions: Vec<f64> = lead
|
||||
.1
|
||||
.lp
|
||||
.segs
|
||||
.iter()
|
||||
.scan(0.0, |before, s| {
|
||||
let f = *before / lead_len;
|
||||
*before += s.length();
|
||||
Some(f)
|
||||
})
|
||||
.collect();
|
||||
let mut out: Vec<(Plane, NumberedLoop)> = Vec::new();
|
||||
let mut wires: Vec<mt::Wire> = Vec::new();
|
||||
// Per section, the profile segments under each of its wire's edges.
|
||||
let mut edge_sources: Vec<Vec<Vec<usize>>> = Vec::new();
|
||||
for (p, l) in &oriented {
|
||||
let c = l.lp.centroid();
|
||||
// Break angles: the lead section's vertex directions seen in this plane.
|
||||
let angles: Vec<f64> = lead_dirs.iter().map(|d| Vec2::new(d.dot(p.x), d.dot(p.y)).angle()).collect();
|
||||
let mut r = l.resample(n, &angles);
|
||||
// Circle resampling creates increasing local angles. An antiparallel sketch
|
||||
// plane must run clockwise locally to keep the same winding in world space (the lead's
|
||||
// directions go round clockwise there). Curving a run through a right angle does not
|
||||
// reverse a section's winding.
|
||||
let flip = parallel && p.normal().dot(n0) < 0.0;
|
||||
let mut r = l.resample(n, &angles, &fractions, flip);
|
||||
if flip {
|
||||
// plane must run clockwise locally to keep the same winding in world space.
|
||||
// Curving a run through a right angle does not reverse a section's winding.
|
||||
if parallel && p.normal().dot(n0) < 0.0 {
|
||||
r = r.oriented(true);
|
||||
}
|
||||
// Start where every vertex lines up best with the lead's vertex of the same number (the
|
||||
@@ -2072,9 +2036,10 @@ pub(crate) fn loft_section_loops(sections: &[(Plane, NumberedLoop)], reversed: b
|
||||
if let Some(k) = (0..m).min_by(|a, b| fit(*b).total_cmp(&fit(*a))) {
|
||||
r.rotate_left(k);
|
||||
}
|
||||
out.push((*p, r));
|
||||
wires.push(uniform_wire(p, &r.lp)?);
|
||||
edge_sources.push(r.from);
|
||||
}
|
||||
Ok(out)
|
||||
Ok((wires, edge_sources))
|
||||
}
|
||||
|
||||
/// Ruled faces between each two neighbouring section wires; each comes from the section edges
|
||||
|
||||
+83
-266
@@ -9,8 +9,6 @@
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Write as _;
|
||||
|
||||
mod assembly;
|
||||
|
||||
/// Largest IGES file we read.
|
||||
pub const MAX_IGES_BYTES: usize = 512 << 20;
|
||||
const MAX_ENTITIES: usize = 2_000_000;
|
||||
@@ -349,11 +347,6 @@ struct Nurbs {
|
||||
|
||||
impl Nurbs {
|
||||
fn eval(&self, t: f64) -> Option<V3> {
|
||||
let h = self.eval_h(t)?;
|
||||
(h[3].abs() > 1e-300).then(|| [h[0] / h[3], h[1] / h[3], h[2] / h[3]])
|
||||
}
|
||||
/// The homogeneous point (x·w, y·w, z·w, w) at `t`.
|
||||
fn eval_h(&self, t: f64) -> Option<[f64; 4]> {
|
||||
let p = self.deg;
|
||||
let n = self.pts.len();
|
||||
if n == 0 || self.knots.len() != n + p + 1 {
|
||||
@@ -375,49 +368,14 @@ impl Nurbs {
|
||||
d[j] = [0, 1, 2, 3].map(|c| (1.0 - alpha) * x[c] + alpha * y[c]);
|
||||
}
|
||||
}
|
||||
d.get(p).copied()
|
||||
let h = d[p];
|
||||
(h[3].abs() > 1e-300).then(|| [h[0] / h[3], h[1] / h[3], h[2] / h[3]])
|
||||
}
|
||||
fn range(&self) -> (f64, f64) {
|
||||
(self.knots.get(self.deg).copied().unwrap_or(0.0), self.knots.get(self.pts.len()).copied().unwrap_or(0.0))
|
||||
}
|
||||
}
|
||||
|
||||
/// A circular arc in its definition plane (at height `c[2]`), counter-clockwise from `a0` to
|
||||
/// `a1` (radians, `a1 > a0`).
|
||||
struct Arc {
|
||||
c: V3,
|
||||
rad: f64,
|
||||
a0: f64,
|
||||
a1: f64,
|
||||
}
|
||||
|
||||
impl Arc {
|
||||
/// The arc placed by `x`, as an exact rational quadratic B-spline (pieces of at most a
|
||||
/// quarter turn).
|
||||
fn nurbs(&self, x: &Xf) -> Nurbs {
|
||||
let sweep = self.a1 - self.a0;
|
||||
let pieces = (sweep / std::f64::consts::FRAC_PI_2).ceil().clamp(1.0, 8.0) as usize;
|
||||
let step = sweep / pieces as f64;
|
||||
let w = (step / 2.0).cos();
|
||||
let on = |t: f64, k: f64| x.point([self.c[0] + k * t.cos(), self.c[1] + k * t.sin(), self.c[2]]);
|
||||
let mut pts = Vec::with_capacity(2 * pieces + 1);
|
||||
let mut knots = vec![0.0; 3];
|
||||
for i in 0..pieces {
|
||||
let t = self.a0 + step * i as f64;
|
||||
let (p, m) = (on(t, self.rad), on(t + step / 2.0, self.rad / w));
|
||||
pts.push([p[0], p[1], p[2], 1.0]);
|
||||
pts.push([m[0] * w, m[1] * w, m[2] * w, w]);
|
||||
if i > 0 {
|
||||
knots.extend([i as f64 / pieces as f64; 2]);
|
||||
}
|
||||
}
|
||||
let p = on(self.a1, self.rad);
|
||||
pts.push([p[0], p[1], p[2], 1.0]);
|
||||
knots.extend([1.0; 3]);
|
||||
Nurbs { deg: 2, knots, pts }
|
||||
}
|
||||
}
|
||||
|
||||
struct Tr<'a> {
|
||||
f: &'a Iges,
|
||||
o: Out,
|
||||
@@ -465,11 +423,6 @@ impl<'a> Tr<'a> {
|
||||
}
|
||||
/// The entity's own transformation (its chain), in millimetres.
|
||||
fn own_xf(&self, seq: i64, depth: usize) -> R<Xf> {
|
||||
self.own_xf_in(seq, depth, self.f.unit)
|
||||
}
|
||||
/// The entity's own transformation with translations in units of `unit` millimetres (1 for
|
||||
/// a curve in a surface's parameter space, which has no length unit).
|
||||
fn own_xf_in(&self, seq: i64, depth: usize, unit: f64) -> R<Xf> {
|
||||
let de = self.de(seq)?;
|
||||
if de.xform <= 0 || depth > MAX_DEPTH {
|
||||
return Ok(Xf::ID);
|
||||
@@ -484,15 +437,13 @@ impl<'a> Tr<'a> {
|
||||
for (col, x) in r.iter_mut().enumerate() {
|
||||
*x = self.n(t, 1 + row * 4 + col)?;
|
||||
}
|
||||
r[3] *= unit;
|
||||
r[3] *= self.f.unit;
|
||||
}
|
||||
let parent = self.own_xf_in(t, depth + 1, unit)?;
|
||||
let parent = self.own_xf(t, depth + 1)?;
|
||||
Ok(parent.then(&Xf(m)))
|
||||
}
|
||||
fn pt(&self, seq: i64, i: usize) -> R<V3> {
|
||||
self.pt_in(seq, i, self.f.unit)
|
||||
}
|
||||
fn pt_in(&self, seq: i64, i: usize, u: f64) -> R<V3> {
|
||||
let u = self.f.unit;
|
||||
Ok([self.n(seq, i)? * u, self.n(seq, i + 1)? * u, self.n(seq, i + 2)? * u])
|
||||
}
|
||||
/// A point entity (116) or direction (123), placed.
|
||||
@@ -538,8 +489,20 @@ impl<'a> Tr<'a> {
|
||||
Ok(vec![Seg::along(c, |t| add(a, mul(sub(b, a), t)))])
|
||||
}
|
||||
100 => {
|
||||
let Arc { c, rad, a0, a1 } = self.arc(seq)?;
|
||||
let zt = c[2];
|
||||
let u = self.f.unit;
|
||||
let zt = self.n(seq, 1)? * u;
|
||||
let c = [self.n(seq, 2)? * u, self.n(seq, 3)? * u, zt];
|
||||
let s = [self.n(seq, 4)? * u, self.n(seq, 5)? * u, zt];
|
||||
let e = [self.n(seq, 6)? * u, self.n(seq, 7)? * u, zt];
|
||||
let rad = norm(sub(s, c));
|
||||
if !(rad > 0.0) {
|
||||
return Err(format!("entity {seq}: arc of zero radius"));
|
||||
}
|
||||
let a0 = (s[1] - c[1]).atan2(s[0] - c[0]);
|
||||
let mut a1 = (e[1] - c[1]).atan2(e[0] - c[0]);
|
||||
while a1 <= a0 + 1e-12 {
|
||||
a1 += std::f64::consts::TAU;
|
||||
}
|
||||
let at = |t: f64| x.point([c[0] + rad * t.cos(), c[1] + rad * t.sin(), zt]);
|
||||
let z = unit(x.dir([0.0, 0.0, 1.0])).ok_or("degenerate arc frame")?;
|
||||
let xa = unit(x.dir([1.0, 0.0, 0.0])).ok_or("degenerate arc frame")?;
|
||||
@@ -608,62 +571,7 @@ impl<'a> Tr<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A circular arc (100) in its definition plane, in millimetres.
|
||||
fn arc(&self, seq: i64) -> R<Arc> {
|
||||
let u = self.f.unit;
|
||||
let zt = self.n(seq, 1)? * u;
|
||||
let c = [self.n(seq, 2)? * u, self.n(seq, 3)? * u, zt];
|
||||
let s = [self.n(seq, 4)? * u, self.n(seq, 5)? * u, zt];
|
||||
let e = [self.n(seq, 6)? * u, self.n(seq, 7)? * u, zt];
|
||||
let rad = norm(sub(s, c));
|
||||
if !(rad > 0.0) {
|
||||
return Err(format!("entity {seq}: arc of zero radius"));
|
||||
}
|
||||
let a0 = (s[1] - c[1]).atan2(s[0] - c[0]);
|
||||
let mut a1 = (e[1] - c[1]).atan2(e[0] - c[0]);
|
||||
while a1 <= a0 + 1e-12 {
|
||||
a1 += std::f64::consts::TAU;
|
||||
}
|
||||
Ok(Arc { c, rad, a0, a1 })
|
||||
}
|
||||
|
||||
/// A surface of revolution (120) whose generatrix is the circular arc `seq`, about the axis
|
||||
/// through `o` along `d`. A STEP surface of revolution turns the whole of its curve, and the
|
||||
/// whole circle turns into a whole sphere or torus (a sphere twice over when the arc is
|
||||
/// centred on the axis): the face's trim cannot pick its piece out of that, and the face
|
||||
/// meshed as the full ball. An arc in a plane through the axis is a sphere or a torus; any
|
||||
/// other arc turns as an exact rational B-spline of just the arc.
|
||||
fn revolved_arc(&mut self, seq: i64, xf: &Xf, o: V3, d: V3) -> R<u64> {
|
||||
let x = xf.then(&self.own_xf(seq, 0)?);
|
||||
let arc = self.arc(seq)?;
|
||||
let n = unit(x.dir([0.0, 0.0, 1.0])).ok_or("degenerate arc frame")?;
|
||||
let (centre, rad) = (x.point(arc.c), arc.rad * x.scale());
|
||||
let off = sub(centre, o);
|
||||
let h = dot(off, d);
|
||||
let rho = norm(sub(off, mul(d, h)));
|
||||
let tol = self.tol.max(rad * 1e-9);
|
||||
if dot(n, d).abs() < 1e-7 && dot(off, n).abs() <= tol {
|
||||
let ax = self.o.placement(add(o, mul(d, h)), d, perp(d));
|
||||
if rho <= tol {
|
||||
return Ok(self.o.add(format!("SPHERICAL_SURFACE('',#{ax},{})", r(rad))));
|
||||
}
|
||||
if rad < rho {
|
||||
return Ok(self.o.add(format!("TOROIDAL_SURFACE('',#{ax},{},{})", r(rho), r(rad))));
|
||||
}
|
||||
}
|
||||
let nb = arc.nurbs(&x);
|
||||
let curve = self.write_nurbs_curve(&nb);
|
||||
let (pa, dd) = (self.o.point(o), self.o.dir(d));
|
||||
let a1 = self.o.add(format!("AXIS1_PLACEMENT('',#{pa},#{dd})"));
|
||||
Ok(self.o.add(format!("SURFACE_OF_REVOLUTION('',#{curve},#{a1})")))
|
||||
}
|
||||
|
||||
fn nurbs_curve(&self, seq: i64, x: &Xf) -> R<Nurbs> {
|
||||
self.nurbs_curve_in(seq, x, self.f.unit)
|
||||
}
|
||||
fn nurbs_curve_in(&self, seq: i64, x: &Xf, unit: f64) -> R<Nurbs> {
|
||||
/// Knot spans shorter than this are moved onto (0, 1).
|
||||
const MIN_KNOT_SPAN: f64 = 1e-4;
|
||||
let k = self.i(seq, 1)?;
|
||||
let m = self.i(seq, 2)?;
|
||||
if !(0..=MAX_LIST as i64).contains(&k) || !(1..=32).contains(&m) || m > k.max(1) + 1 {
|
||||
@@ -683,27 +591,17 @@ impl<'a> Tr<'a> {
|
||||
if !(w > 0.0) {
|
||||
return Err(format!("entity {seq}: non-positive weight"));
|
||||
}
|
||||
let p = x.point(self.pt_in(seq, base_p + 3 * j, unit)?);
|
||||
let p = x.point(self.pt(seq, base_p + 3 * j)?);
|
||||
pts.push([p[0] * w, p[1] * w, p[2] * w, w]);
|
||||
}
|
||||
if knots.windows(2).any(|w| w[1] < w[0]) {
|
||||
return Err(format!("entity {seq}: knots out of order"));
|
||||
}
|
||||
let mut nb = Nurbs { deg: m, knots, pts };
|
||||
let nb = Nurbs { deg: m, knots, pts };
|
||||
let (a, b) = nb.range();
|
||||
if !(b > a) {
|
||||
return Err(format!("entity {seq}: empty parameter range"));
|
||||
}
|
||||
// Some exporters write a curve over a knot span of 1e-7 or less. The STEP side reads a
|
||||
// span that small as a single value and refused the curve, losing the faces it bounds.
|
||||
// Moving and scaling the knots onto (0, 1) leaves the curve's shape as it is; nothing
|
||||
// else refers to its parameters.
|
||||
if b - a < MIN_KNOT_SPAN {
|
||||
let scale = 1.0 / (b - a);
|
||||
for k in &mut nb.knots {
|
||||
*k = (*k - a) * scale;
|
||||
}
|
||||
}
|
||||
Ok(nb)
|
||||
}
|
||||
|
||||
@@ -886,9 +784,6 @@ impl<'a> Tr<'a> {
|
||||
let ax_x = x.then(&self.own_xf(axis, 0)?);
|
||||
let (a, b) = (ax_x.point(self.pt(axis, 1)?), ax_x.point(self.pt(axis, 4)?));
|
||||
let d = unit(sub(b, a)).ok_or("zero-length revolution axis")?;
|
||||
if self.de(generatrix)?.typ == 100 {
|
||||
return self.revolved_arc(generatrix, &x, a, d);
|
||||
}
|
||||
let segs = self.curve(generatrix, &x, 1)?;
|
||||
let [seg] = segs.as_slice() else { return Err(format!("entity {seq}: composite generatrix is not read")) };
|
||||
let (pa, dd) = (self.o.point(a), self.o.dir(d));
|
||||
@@ -911,61 +806,6 @@ impl<'a> Tr<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The start point of a curve in a surface's parameter space (the B curve of a curve on a
|
||||
/// surface, 142): its (u, v) are the first two coordinates. Lines, arcs, B-splines and
|
||||
/// composites of them, as the specification lists for parameter-space curves.
|
||||
fn param_start(&self, seq: i64, depth: usize) -> R<V3> {
|
||||
if depth > MAX_DEPTH {
|
||||
return Err("parameter-space curves nested too deeply".into());
|
||||
}
|
||||
let de = self.de(seq)?;
|
||||
let x = self.own_xf_in(seq, 0, 1.0)?;
|
||||
let p = match de.typ {
|
||||
110 => self.pt_in(seq, 1, 1.0)?,
|
||||
100 => [self.n(seq, 4)?, self.n(seq, 5)?, self.n(seq, 1)?],
|
||||
126 => {
|
||||
let nb = self.nurbs_curve_in(seq, &Xf::ID, 1.0)?;
|
||||
nb.eval(nb.range().0).ok_or_else(|| format!("entity {seq}: B-spline cannot be evaluated"))?
|
||||
}
|
||||
102 if self.i(seq, 1)? > 0 => self.param_start(self.i(seq, 2)?, depth + 1)?,
|
||||
t => return Err(format!("parameter-space curve type {t} is not read")),
|
||||
};
|
||||
Ok(x.point(p))
|
||||
}
|
||||
|
||||
/// The point of a B-spline surface (128) at parameters (u, v), placed as `surface` places it.
|
||||
fn surface_point(&self, seq: i64, xf: &Xf, u: f64, v: f64) -> R<V3> {
|
||||
if self.de(seq)?.typ != 128 {
|
||||
return Err(format!("entity {seq}: only B-spline surfaces are evaluated"));
|
||||
}
|
||||
let x = xf.then(&self.own_xf(seq, 0)?);
|
||||
let (k1, k2, m1, m2) = (self.i(seq, 1)?, self.i(seq, 2)?, self.i(seq, 3)?, self.i(seq, 4)?);
|
||||
if !(0..=4096).contains(&k1) || !(0..=4096).contains(&k2) || !(1..=32).contains(&m1) || !(1..=32).contains(&m2) {
|
||||
return Err(format!("entity {seq}: bad B-spline surface size"));
|
||||
}
|
||||
let (k1, k2, m1, m2) = (k1 as usize, k2 as usize, m1 as usize, m2 as usize);
|
||||
let (n1, n2) = (k1 + m1 + 2, k2 + m2 + 2);
|
||||
let s_knots: Vec<f64> = (0..n1).map(|j| self.n(seq, 10 + j)).collect::<R<_>>()?;
|
||||
let t_knots: Vec<f64> = (0..n2).map(|j| self.n(seq, 10 + n1 + j)).collect::<R<_>>()?;
|
||||
let base_w = 10 + n1 + n2;
|
||||
let base_p = base_w + (k1 + 1) * (k2 + 1);
|
||||
// Each row of the net at u, then the column of those points at v (homogeneous, so the
|
||||
// weights combine as the rational tensor product does).
|
||||
let mut column = Vec::with_capacity(k2 + 1);
|
||||
for j in 0..=k2 {
|
||||
let mut row = Vec::with_capacity(k1 + 1);
|
||||
for i in 0..=k1 {
|
||||
let idx = j * (k1 + 1) + i;
|
||||
let w = self.n(seq, base_w + idx)?;
|
||||
let p = x.point(self.pt(seq, base_p + 3 * idx)?);
|
||||
row.push([p[0] * w, p[1] * w, p[2] * w, w]);
|
||||
}
|
||||
let h = Nurbs { deg: m1, knots: s_knots.clone(), pts: row }.eval_h(u).ok_or("surface cannot be evaluated")?;
|
||||
column.push(h);
|
||||
}
|
||||
Nurbs { deg: m2, knots: t_knots, pts: column }.eval(v).ok_or_else(|| "surface cannot be evaluated".into())
|
||||
}
|
||||
|
||||
/// The natural boundary of a B-spline surface (its four edge curves), for trimmed surfaces
|
||||
/// with no outer curve.
|
||||
fn natural_boundary(&mut self, seq: i64, xf: &Xf) -> R<Vec<Seg>> {
|
||||
@@ -1242,42 +1082,77 @@ fn translate(text: &str) -> std::result::Result<(String, Vec<String>), String> {
|
||||
// Entities used by others (a B-rep's faces, a trimmed surface's curves) are not roots;
|
||||
// physically dependent entities have status digits 01 in columns 3–4, but files are lax:
|
||||
// collect references instead.
|
||||
let assembly = assembly::Assembly::read(&t, &seqs)?;
|
||||
let mut solids = HashMap::new();
|
||||
let mut solids: Vec<(u64, String)> = Vec::new();
|
||||
let mut styles: Vec<(u64, [f32; 3])> = Vec::new();
|
||||
let mut n = 0usize;
|
||||
let mut fallback = String::new();
|
||||
let watch = crate::watch::current();
|
||||
for &s in &seqs {
|
||||
if watch.as_ref().is_some_and(|w| w.cancelled()) {
|
||||
return Err("IGES import cancelled".into());
|
||||
}
|
||||
let Some(de) = f.des.get(&s) else { continue };
|
||||
if de.typ != 186 {
|
||||
continue;
|
||||
}
|
||||
n += 1;
|
||||
let name = if let Some(name) = assembly::entity_name(&f, s) {
|
||||
name
|
||||
} else {
|
||||
fallback.clear();
|
||||
let _ = write!(fallback, "Body{n}");
|
||||
fallback.as_str()
|
||||
// A name property (406 form 15) among the solid's trailing pointers, else the label.
|
||||
let named = f.params.get(&s).and_then(|p| {
|
||||
p.iter().skip(4).filter_map(|x| int(x)).filter(|x| *x > 0).find_map(|ptr| {
|
||||
let d = f.des.get(&usize::try_from(ptr).ok()?)?;
|
||||
(d.typ == 406 && d.form == 15).then(|| f.params.get(&usize::try_from(ptr).ok()?)?.get(2).cloned()).flatten()
|
||||
})
|
||||
});
|
||||
let name = match named.filter(|x| !x.trim().is_empty()) {
|
||||
Some(x) => x.trim().to_string(),
|
||||
None if de.label.is_empty() => format!("Body{n}"),
|
||||
None => de.label.clone(),
|
||||
};
|
||||
match brep(&mut t, s as i64, &mut styles) {
|
||||
Ok((id, color)) => {
|
||||
let named = {
|
||||
// Re-label the solid with its name.
|
||||
let line = t.o.lines.get(id as usize - 1).cloned().unwrap_or_default();
|
||||
line.replacen("('',", &format!("('{}',", name.replace('\'', "''")), 1)
|
||||
};
|
||||
if let Some(l) = t.o.lines.get_mut(id as usize - 1) {
|
||||
*l = l.replacen("('',", &format!("('{}',", name.replace('\'', "''")), 1);
|
||||
*l = named;
|
||||
}
|
||||
if let Some(c) = color {
|
||||
styles.push((id, c));
|
||||
}
|
||||
solids.insert(s, id);
|
||||
solids.push((id, name));
|
||||
}
|
||||
Err(e) => t.warn(format!("solid {name}: not read: {e}")),
|
||||
}
|
||||
}
|
||||
assembly.write(&mut t, &seqs, &solids, &mut styles, ctx)?;
|
||||
// Trimmed and bounded surfaces not used by anything else: sewn into shells.
|
||||
let mut faces = Vec::new();
|
||||
let mut sw = Sewer { tol, verts: Vec::new(), grid: HashMap::new(), edges: Vec::new(), by_ends: HashMap::new() };
|
||||
if solids.is_empty() {
|
||||
for &s in &seqs {
|
||||
let Some(de) = f.des.get(&s) else { continue };
|
||||
if de.typ != 144 && de.typ != 143 && !(de.typ == 128 && is_root(&f, s)) {
|
||||
continue;
|
||||
}
|
||||
match trimmed(&mut t, &mut sw, s as i64) {
|
||||
Ok(fb) => faces.push(fb),
|
||||
Err(e) => t.warn(format!("surface {s}: not read: {e}")),
|
||||
}
|
||||
}
|
||||
if !faces.is_empty() {
|
||||
orient(&mut faces);
|
||||
let (shell, closed) = write_shell(&mut t.o, &sw, &faces, &mut styles);
|
||||
let item = if closed {
|
||||
t.o.add(format!("MANIFOLD_SOLID_BREP('Body1',#{shell})"))
|
||||
} else {
|
||||
t.warn("the surfaces do not close into a solid: imported as an open body");
|
||||
t.o.add(format!("SHELL_BASED_SURFACE_MODEL('Body1',(#{shell}))"))
|
||||
};
|
||||
solids.push((item, "Body1".into()));
|
||||
}
|
||||
}
|
||||
if solids.is_empty() {
|
||||
let why = t.warnings.first().cloned().unwrap_or_else(|| "no solids or trimmed surfaces".into());
|
||||
return Err(format!("IGES import: nothing to read ({why})"));
|
||||
}
|
||||
let items = solids.iter().map(|(i, _)| format!("#{i}")).collect::<Vec<_>>().join(",");
|
||||
t.o.add(format!("ADVANCED_BREP_SHAPE_REPRESENTATION('',({items}),#{ctx})"));
|
||||
for (item, c) in styles {
|
||||
let rgb = t.o.add(format!("COLOUR_RGB('',{},{},{})", r(c[0] as f64), r(c[1] as f64), r(c[2] as f64)));
|
||||
let fasc = t.o.add(format!("FILL_AREA_STYLE_COLOUR('',#{rgb})"));
|
||||
@@ -1298,42 +1173,12 @@ fn translate(text: &str) -> std::result::Result<(String, Vec<String>), String> {
|
||||
Ok((s, t.warnings))
|
||||
}
|
||||
|
||||
/// Sew surfaces within their owning group, keeping different parts separate.
|
||||
fn sew_surfaces(
|
||||
t: &mut Tr,
|
||||
seqs: impl Iterator<Item = usize>,
|
||||
name: &str,
|
||||
styles: &mut Vec<(u64, [f32; 3])>,
|
||||
faces: &mut Vec<FaceB>,
|
||||
sw: &mut Sewer,
|
||||
) -> R<Option<u64>> {
|
||||
faces.clear();
|
||||
sw.verts.clear();
|
||||
sw.grid.clear();
|
||||
sw.edges.clear();
|
||||
sw.by_ends.clear();
|
||||
let watch = crate::watch::current();
|
||||
for seq in seqs {
|
||||
if watch.as_ref().is_some_and(|w| w.cancelled()) {
|
||||
return Err("IGES import cancelled".into());
|
||||
}
|
||||
match trimmed(t, sw, seq as i64) {
|
||||
Ok(face) => faces.push(face),
|
||||
Err(e) => t.warn(format!("surface {seq}: not read: {e}")),
|
||||
}
|
||||
}
|
||||
if faces.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
orient(faces);
|
||||
let (shell, closed) = write_shell(&mut t.o, sw, faces, styles);
|
||||
let name = name.replace('\'', "''");
|
||||
Ok(Some(if closed {
|
||||
t.o.add(format!("MANIFOLD_SOLID_BREP('{name}',#{shell})"))
|
||||
} else {
|
||||
t.warn("the surfaces do not close into a solid: imported as an open body");
|
||||
t.o.add(format!("SHELL_BASED_SURFACE_MODEL('{name}',(#{shell}))"))
|
||||
}))
|
||||
/// A surface entity nobody refers to (a bare B-spline patch is a face of its own).
|
||||
fn is_root(f: &Iges, seq: usize) -> bool {
|
||||
let target = seq.to_string();
|
||||
!f.params
|
||||
.iter()
|
||||
.any(|(s, p)| *s != seq && f.des.get(s).is_some_and(|d| d.typ != 406 && d.typ != 402) && p.iter().skip(1).any(|x| x.trim() == target))
|
||||
}
|
||||
|
||||
/// A trimmed (144) or bounded (143) surface, or a bare B-spline surface, as a face.
|
||||
@@ -1352,10 +1197,10 @@ fn trimmed(t: &mut Tr, sw: &mut Sewer, seq: i64) -> R<FaceB> {
|
||||
let n1 = t.i(seq, 2)?;
|
||||
let n2 = t.i(seq, 3)?.clamp(0, MAX_LIST as i64) as usize;
|
||||
let mut loops = Vec::new();
|
||||
let outer = if n1 == 0 { t.natural_boundary(surf_seq, &xf)? } else { cos_curve(t, t.i(seq, 4)?, &xf, surf_seq)? };
|
||||
let outer = if n1 == 0 { t.natural_boundary(surf_seq, &xf)? } else { cos_curve(t, t.i(seq, 4)?, &xf)? };
|
||||
loops.push(loop_of(t, sw, outer));
|
||||
for k in 0..n2 {
|
||||
let segs = cos_curve(t, t.i(seq, 5 + k)?, &xf, surf_seq)?;
|
||||
let segs = cos_curve(t, t.i(seq, 5 + k)?, &xf)?;
|
||||
loops.push(loop_of(t, sw, segs));
|
||||
}
|
||||
loops.retain(|l| !l.is_empty());
|
||||
@@ -1389,16 +1234,8 @@ fn trimmed(t: &mut Tr, sw: &mut Sewer, seq: i64) -> R<FaceB> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The model-space curve of a curve on a surface (142) bounding a trimmed `surface`, its pieces
|
||||
/// head to tail.
|
||||
///
|
||||
/// A curve on a surface is one curve given twice: B in the surface's parameter space and C in
|
||||
/// model space, both running the same way (C = S∘B). A composite C must run each piece on from
|
||||
/// the end of the one before, but some exporters write its pieces in order with some of them
|
||||
/// reversed, so the loop does not close and the face is lost. The pieces are turned to run on,
|
||||
/// starting where S(B) starts (the end of the first piece there), so the loop also keeps the
|
||||
/// sense the file gives it (outer loop and holes the opposite ways round).
|
||||
fn cos_curve(t: &mut Tr, seq: i64, xf: &Xf, surface: i64) -> R<Vec<Seg>> {
|
||||
/// The model-space curve of a curve on a surface (142).
|
||||
fn cos_curve(t: &mut Tr, seq: i64, xf: &Xf) -> R<Vec<Seg>> {
|
||||
let de = t.de(seq)?;
|
||||
if de.typ != 142 {
|
||||
return t.curve(seq, xf, 0);
|
||||
@@ -1408,27 +1245,7 @@ fn cos_curve(t: &mut Tr, seq: i64, xf: &Xf, surface: i64) -> R<Vec<Seg>> {
|
||||
if c <= 0 {
|
||||
return Err("a curve on a surface without its model-space curve".into());
|
||||
}
|
||||
let segs = t.curve(c, &x, 0)?;
|
||||
let b = t.i(seq, 3).unwrap_or(0);
|
||||
let start = if b > 0 { t.param_start(b, 0).and_then(|p| t.surface_point(surface, xf, p[0], p[1])).ok() } else { None };
|
||||
Ok(head_to_tail(segs, start, t.tol))
|
||||
}
|
||||
|
||||
/// Pieces of a composite curve turned so that each starts where the one before ends, the first
|
||||
/// at the end nearer `start` (when known). A closed piece (its ends within `tol`, the sewing
|
||||
/// tolerance that decides they are one vertex) keeps its direction.
|
||||
fn head_to_tail(segs: Vec<Seg>, start: Option<V3>, tol: f64) -> Vec<Seg> {
|
||||
let mut prev = start;
|
||||
segs.into_iter()
|
||||
.map(|s| {
|
||||
let s = match prev {
|
||||
Some(p) if norm(sub(s.a, s.b)) > tol && norm(sub(s.b, p)) < norm(sub(s.a, p)) => s.reversed(),
|
||||
_ => s,
|
||||
};
|
||||
prev = Some(s.b);
|
||||
s
|
||||
})
|
||||
.collect()
|
||||
t.curve(c, &x, 0)
|
||||
}
|
||||
|
||||
/// The model-space curves of a boundary (141), each in its sense.
|
||||
|
||||
@@ -1,280 +0,0 @@
|
||||
//! IGES groups (402) and subfigures (308/408), from the published IGES specification.
|
||||
//! Definitions become STEP products; instances refer to them without copying geometry.
|
||||
//! Reference: https://nvlpubs.nist.gov/nistpubs/Legacy/IR/nbsir88-3813.pdf
|
||||
use super::*;
|
||||
use std::collections::HashSet;
|
||||
|
||||
const MAX_GROUPS: usize = 10_000;
|
||||
const MAX_INSTANCES: usize = 100_000;
|
||||
const MAX_REFERENCES: usize = 4 * MAX_ENTITIES;
|
||||
|
||||
struct Group {
|
||||
seq: usize,
|
||||
members: Vec<usize>,
|
||||
}
|
||||
|
||||
struct Instance {
|
||||
definition: usize,
|
||||
transform: Xf,
|
||||
}
|
||||
|
||||
pub(super) struct Assembly {
|
||||
groups: Vec<Group>,
|
||||
indices: HashMap<usize, usize>,
|
||||
instances: HashMap<usize, Instance>,
|
||||
referenced: HashSet<usize>,
|
||||
surface_references: HashSet<usize>,
|
||||
}
|
||||
|
||||
impl Assembly {
|
||||
pub(super) fn read(t: &Tr, seqs: &[usize]) -> R<Self> {
|
||||
let mut out = Self {
|
||||
groups: Vec::new(),
|
||||
indices: HashMap::new(),
|
||||
instances: HashMap::new(),
|
||||
referenced: HashSet::new(),
|
||||
surface_references: HashSet::new(),
|
||||
};
|
||||
let mut references = 0usize;
|
||||
let watch = crate::watch::current();
|
||||
for &seq in seqs {
|
||||
if watch.as_ref().is_some_and(|w| w.cancelled()) {
|
||||
return Err("IGES import cancelled".into());
|
||||
}
|
||||
let de = t.de(seq as i64)?;
|
||||
if de.typ == 308 || (de.typ == 402 && matches!(de.form, 1 | 7 | 14 | 15)) {
|
||||
if out.groups.len() >= MAX_GROUPS {
|
||||
return Err("too many IGES assembly definitions".into());
|
||||
}
|
||||
let field = if de.typ == 308 { 3 } else { 1 };
|
||||
let count = usize::try_from(t.i(seq as i64, field)?).map_err(|_| "negative IGES group size")?;
|
||||
references = references.saturating_add(count);
|
||||
if count > MAX_LIST || references > MAX_REFERENCES {
|
||||
return Err("IGES assembly references exceed the work limit".into());
|
||||
}
|
||||
let p = t.p(seq as i64)?;
|
||||
let entries = p.get(field + 1..field + 1 + count).ok_or("truncated IGES group")?;
|
||||
let mut members = Vec::with_capacity(count);
|
||||
for entry in entries {
|
||||
let child = int(entry).and_then(|x| usize::try_from(x).ok()).filter(|x| *x > 0).ok_or("invalid IGES group reference")?;
|
||||
t.de(child as i64)?;
|
||||
members.push(child);
|
||||
out.referenced.insert(child);
|
||||
}
|
||||
out.indices.insert(seq, out.groups.len());
|
||||
out.groups.push(Group { seq, members });
|
||||
} else if de.typ == 408 {
|
||||
if out.instances.len() >= MAX_INSTANCES {
|
||||
return Err("too many IGES assembly instances".into());
|
||||
}
|
||||
let definition = usize::try_from(t.i(seq as i64, 1)?).map_err(|_| "invalid IGES subfigure reference")?;
|
||||
if t.de(definition as i64)?.typ != 308 {
|
||||
return Err("IGES instance does not refer to a subfigure definition".into());
|
||||
}
|
||||
let p = t.p(seq as i64)?;
|
||||
let scale = match p.get(5).map(|s| s.trim()) {
|
||||
None | Some("") => 1.0,
|
||||
Some(s) => num(s).filter(|x| *x != 0.0).ok_or("invalid IGES instance scale")?,
|
||||
};
|
||||
let [x, y, z] = t.pt(seq as i64, 2)?;
|
||||
let local = Xf([[scale, 0.0, 0.0, x], [0.0, scale, 0.0, y], [0.0, 0.0, scale, z]]);
|
||||
let transform = t.own_xf(seq as i64, 0)?.then(&local).then(&t.own_xf(definition as i64, 0)?);
|
||||
if !transform.0.iter().flatten().all(|v| v.is_finite()) {
|
||||
return Err("non-finite IGES instance placement".into());
|
||||
}
|
||||
out.instances.insert(seq, Instance { definition, transform });
|
||||
out.referenced.insert(definition);
|
||||
}
|
||||
}
|
||||
// Index geometry references once instead of rescanning all parameters for each patch.
|
||||
for (&seq, params) in &t.f.params {
|
||||
if watch.as_ref().is_some_and(|w| w.cancelled()) {
|
||||
return Err("IGES import cancelled".into());
|
||||
}
|
||||
if t.f.des.get(&seq).is_some_and(|d| matches!(d.typ, 308 | 402 | 406 | 408)) {
|
||||
continue;
|
||||
}
|
||||
for p in params.iter().skip(1) {
|
||||
let p = p.trim();
|
||||
if p.starts_with('0') {
|
||||
continue;
|
||||
}
|
||||
if let Ok(id) = p.parse::<usize>()
|
||||
&& id != seq
|
||||
&& t.f.des.get(&id).is_some_and(|d| d.typ == 128)
|
||||
{
|
||||
out.surface_references.insert(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut depths = HashMap::with_capacity(out.groups.len());
|
||||
let mut placements = out.groups.iter().filter(|g| !out.referenced.contains(&g.seq)).count()
|
||||
+ out.instances.keys().filter(|s| !out.referenced.contains(*s)).count();
|
||||
for group in &out.groups {
|
||||
placements += group.members.iter().filter(|s| out.indices.contains_key(*s) || out.instances.contains_key(*s)).count();
|
||||
if placements > MAX_INSTANCES {
|
||||
return Err("too many IGES assembly placements".into());
|
||||
}
|
||||
out.depth(group.seq, 0, &mut depths)?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn depth(&self, seq: usize, depth: usize, seen: &mut HashMap<usize, Option<usize>>) -> R<usize> {
|
||||
if depth >= MAX_DEPTH {
|
||||
return Err("IGES assembly nesting is too deep".into());
|
||||
}
|
||||
if let Some(height) = seen.get(&seq) {
|
||||
return height.ok_or_else(|| "cyclic IGES assembly".into());
|
||||
}
|
||||
seen.insert(seq, None);
|
||||
let group = self.indices.get(&seq).and_then(|i| self.groups.get(*i)).ok_or("missing IGES assembly definition")?;
|
||||
let mut height = 1;
|
||||
for child in &group.members {
|
||||
let definition = self.instances.get(child).map(|i| i.definition).unwrap_or(*child);
|
||||
if self.indices.contains_key(&definition) {
|
||||
height = height.max(1 + self.depth(definition, depth + 1, seen)?);
|
||||
}
|
||||
}
|
||||
if height > MAX_DEPTH {
|
||||
return Err("IGES assembly nesting is too deep".into());
|
||||
}
|
||||
seen.insert(seq, Some(height));
|
||||
Ok(height)
|
||||
}
|
||||
|
||||
pub(super) fn write(&self, t: &mut Tr, seqs: &[usize], solids: &HashMap<usize, u64>, styles: &mut Vec<(u64, [f32; 3])>, ctx: u64) -> R<()> {
|
||||
let app = t.o.add("APPLICATION_CONTEXT('mechanical design')");
|
||||
let pc = t.o.add(format!("PRODUCT_CONTEXT('',#{app},'mechanical')"));
|
||||
let dc = t.o.add(format!("PRODUCT_DEFINITION_CONTEXT('part definition',#{app},'design')"));
|
||||
let origin = t.o.placement([0.0; 3], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]);
|
||||
let mut products = HashMap::with_capacity(self.groups.len() + 1);
|
||||
let mut items = Vec::new();
|
||||
let mut list = String::new();
|
||||
let mut fallback = String::new();
|
||||
let mut made = 0usize;
|
||||
let f = t.f;
|
||||
let mut faces = Vec::new();
|
||||
let mut sewer = Sewer { tol: t.tol, verts: Vec::new(), grid: HashMap::new(), edges: Vec::new(), by_ends: HashMap::new() };
|
||||
let watch = crate::watch::current();
|
||||
// A synthetic root holds loose geometry and top-level groups/instances.
|
||||
for group in std::iter::once(None).chain(self.groups.iter().map(Some)) {
|
||||
if watch.as_ref().is_some_and(|w| w.cancelled()) {
|
||||
return Err("IGES import cancelled".into());
|
||||
}
|
||||
let seq = group.map(|g| g.seq).unwrap_or(0);
|
||||
let name = if seq == 0 {
|
||||
"Import"
|
||||
} else if let Some(name) = entity_name(f, seq) {
|
||||
name
|
||||
} else {
|
||||
fallback.clear();
|
||||
let _ = write!(fallback, "Group {seq}");
|
||||
fallback.as_str()
|
||||
};
|
||||
items.clear();
|
||||
let members = group.map(|g| g.members.as_slice()).unwrap_or(seqs);
|
||||
items.extend(members.iter().filter(|s| seq != 0 || !self.referenced.contains(*s)).filter_map(|s| solids.get(s).copied()));
|
||||
let surfaces = members
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|s| seq != 0 || !self.referenced.contains(s))
|
||||
.filter(|s| f.des.get(s).is_some_and(|d| matches!(d.typ, 143 | 144) || (d.typ == 128 && !self.surface_references.contains(s))));
|
||||
if let Some(item) = sew_surfaces(t, surfaces, if seq == 0 { "Body1" } else { name }, styles, &mut faces, &mut sewer)? {
|
||||
items.push(item);
|
||||
}
|
||||
made += items.len();
|
||||
list.clear();
|
||||
let _ = write!(list, "#{origin}");
|
||||
for item in &items {
|
||||
let _ = write!(list, ",#{item}");
|
||||
}
|
||||
let rep = t.o.add(format!("ADVANCED_BREP_SHAPE_REPRESENTATION('',({list}),#{ctx})"));
|
||||
let name = name.replace('\'', "''");
|
||||
let product = t.o.add(format!("PRODUCT('{name}','{name}','',(#{pc}))"));
|
||||
let formation = t.o.add(format!("PRODUCT_DEFINITION_FORMATION('','',#{product})"));
|
||||
let pd = t.o.add(format!("PRODUCT_DEFINITION('design','',#{formation},#{dc})"));
|
||||
let shape = t.o.add(format!("PRODUCT_DEFINITION_SHAPE('','',#{pd})"));
|
||||
t.o.add(format!("SHAPE_DEFINITION_REPRESENTATION(#{shape},#{rep})"));
|
||||
products.insert(seq, (pd, rep));
|
||||
}
|
||||
if made == 0 {
|
||||
let why = t.warnings.first().map(String::as_str).unwrap_or("no solids or trimmed surfaces");
|
||||
return Err(format!("IGES import: nothing to read ({why})"));
|
||||
}
|
||||
for group in std::iter::once(None).chain(self.groups.iter().map(Some)) {
|
||||
let parent = group.map(|g| g.seq).unwrap_or(0);
|
||||
let members = group.map(|g| g.members.as_slice()).unwrap_or(seqs);
|
||||
for &child in members {
|
||||
if watch.as_ref().is_some_and(|w| w.cancelled()) {
|
||||
return Err("IGES import cancelled".into());
|
||||
}
|
||||
if parent == 0 && self.referenced.contains(&child) {
|
||||
continue;
|
||||
}
|
||||
let (definition, transform) = match self.instances.get(&child) {
|
||||
Some(i) => (i.definition, i.transform),
|
||||
None if self.indices.contains_key(&child) => (child, t.own_xf(child as i64, 0)?),
|
||||
_ => continue,
|
||||
};
|
||||
let (parent_pd, parent_rep) = products.get(&parent).copied().ok_or("missing IGES assembly parent")?;
|
||||
let (child_pd, child_rep) = products.get(&definition).copied().ok_or("missing IGES assembly child")?;
|
||||
let label = entity_name(f, child).unwrap_or("").replace('\'', "''");
|
||||
let nauo = t.o.add(format!("NEXT_ASSEMBLY_USAGE_OCCURRENCE('{child}','{label}','',#{parent_pd},#{child_pd},$)"));
|
||||
let shape = t.o.add(format!("PRODUCT_DEFINITION_SHAPE('','',#{nauo})"));
|
||||
let op = transformation(&mut t.o, transform)?;
|
||||
let rr = t.o.add(format!("(REPRESENTATION_RELATIONSHIP('','',#{child_rep},#{parent_rep})REPRESENTATION_RELATIONSHIP_WITH_TRANSFORMATION(#{op})SHAPE_REPRESENTATION_RELATIONSHIP())"));
|
||||
t.o.add(format!("CONTEXT_DEPENDENT_SHAPE_REPRESENTATION(#{rr},#{shape})"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn transformation(out: &mut Out, xf: Xf) -> R<u64> {
|
||||
if !xf.0.iter().flatten().all(|v| v.is_finite()) {
|
||||
return Err("non-finite IGES assembly placement".into());
|
||||
}
|
||||
let [x, y, z] = [xf.dir([1.0, 0.0, 0.0]), xf.dir([0.0, 1.0, 0.0]), xf.dir([0.0, 0.0, 1.0])];
|
||||
let [sx, sy, sz] = [norm(x), norm(y), norm(z)];
|
||||
let scale = xf.scale();
|
||||
if [sx, sy, sz, scale].iter().any(|s| !s.is_finite() || *s <= 1e-300) {
|
||||
return Err("singular IGES assembly placement".into());
|
||||
}
|
||||
let (x, y, z, o) = (out.dir(mul(x, 1.0 / sx)), out.dir(mul(y, 1.0 / sy)), out.dir(mul(z, 1.0 / sz)), out.point(xf.point([0.0; 3])));
|
||||
Ok(out.add(format!("CARTESIAN_TRANSFORMATION_OPERATOR_3D_NON_UNIFORM('','',#{x},#{y},#{o},{},#{z},{},{})", r(sx), r(sy), r(sz))))
|
||||
}
|
||||
|
||||
/// Name properties follow the associativity pointers; member pointers are not properties.
|
||||
pub(super) fn entity_name(f: &Iges, seq: usize) -> Option<&str> {
|
||||
let de = f.des.get(&seq)?;
|
||||
let p = f.params.get(&seq)?;
|
||||
let count = |i: usize| p.get(i).and_then(|s| int(s)).and_then(|x| usize::try_from(x).ok()).filter(|n| *n <= MAX_LIST);
|
||||
let end = match de.typ {
|
||||
186 => count(3)?.checked_mul(2)?.checked_add(4)?,
|
||||
308 => count(3)?.checked_add(4)?,
|
||||
402 => count(1)?.checked_add(2)?,
|
||||
408 => 6,
|
||||
_ => p.len(),
|
||||
};
|
||||
let property = (|| {
|
||||
let after = end.checked_add(count(end)?)?.checked_add(1)?;
|
||||
let n = count(after)?;
|
||||
p.get(after + 1..after + 1 + n)?.iter().find_map(|s| {
|
||||
let id = int(s).and_then(|x| usize::try_from(x).ok())?;
|
||||
let d = f.des.get(&id)?;
|
||||
if d.typ != 406 || d.form != 15 {
|
||||
return None;
|
||||
}
|
||||
f.params.get(&id)?.get(2).and_then(|s| name_text(s))
|
||||
})
|
||||
})();
|
||||
property.or_else(|| if de.typ == 308 { p.get(2).and_then(|s| name_text(s)) } else { None }).or_else(|| name_text(&de.label))
|
||||
}
|
||||
|
||||
/// Match the component-name limit before copying or repeating a shared name property.
|
||||
fn name_text(s: &str) -> Option<&str> {
|
||||
let end = s.char_indices().nth(128).map(|(i, _)| i).unwrap_or(s.len());
|
||||
let name = s.get(..end)?.trim();
|
||||
(!name.is_empty()).then_some(name)
|
||||
}
|
||||
@@ -85,16 +85,10 @@ fn hostile_iges_never_panics() {
|
||||
|
||||
/// An IGES file from (type, form, parameters) entities, in order (pointers are 2k + 1).
|
||||
fn iges_file(ents: &[(i64, i64, String)]) -> String {
|
||||
let placed: Vec<(i64, i64, String, i64)> = ents.iter().map(|(t, f, p)| (*t, *f, p.clone(), 0)).collect();
|
||||
iges_file_placed(&placed)
|
||||
}
|
||||
|
||||
/// Like [`iges_file`], with each entity's transformation matrix pointer (0 for none).
|
||||
fn iges_file_placed(ents: &[(i64, i64, String, i64)]) -> String {
|
||||
let mut out = vec![format!("{:<72}S{:>7}", "test", 1), format!("{:<72}G{:>7}", "1H,,1H;,,,,,,,,,,,1.,2,2HMM,,,,1.E-6;", 1)];
|
||||
let mut p_lines: Vec<(usize, String)> = Vec::new();
|
||||
let mut starts = Vec::new();
|
||||
for (k, (t, _, p, _)) in ents.iter().enumerate() {
|
||||
for (k, (t, _, p)) in ents.iter().enumerate() {
|
||||
starts.push(p_lines.len() + 1);
|
||||
let text = format!("{t},{p};");
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
@@ -102,9 +96,9 @@ fn iges_file_placed(ents: &[(i64, i64, String, i64)]) -> String {
|
||||
p_lines.push((2 * k + 1, c.iter().collect()));
|
||||
}
|
||||
}
|
||||
for (k, (t, form, _, xf)) in ents.iter().enumerate() {
|
||||
for (k, (t, form, _)) in ents.iter().enumerate() {
|
||||
let count = p_lines.iter().filter(|(d, _)| *d == 2 * k + 1).count();
|
||||
out.push(format!("{:>8}{:>8}{:>8}{:>8}{:>8}{:>8}{:>8}{:>8}{:>8}D{:>7}", t, starts[k], 0, 0, 0, 0, xf, 0, "00000000", 2 * k + 1));
|
||||
out.push(format!("{:>8}{:>8}{:>8}{:>8}{:>8}{:>8}{:>8}{:>8}{:>8}D{:>7}", t, starts[k], 0, 0, 0, 0, 0, 0, "00000000", 2 * k + 1));
|
||||
out.push(format!("{:>8}{:>8}{:>8}{:>8}{:>8}{:>8}{:>8}{:>8}{:>8}D{:>7}", t, 0, 0, count, form, 0, 0, "", 0, 2 * k + 2));
|
||||
}
|
||||
for (i, (d, l)) in p_lines.iter().enumerate() {
|
||||
@@ -114,158 +108,15 @@ fn iges_file_placed(ents: &[(i64, i64, String, i64)]) -> String {
|
||||
out.join("\n")
|
||||
}
|
||||
|
||||
/// A spherical cap written the way analytic IGES exports write one: a surface of revolution
|
||||
/// (120) whose generatrix is a short circular arc (100) centred on the axis, turned into the
|
||||
/// meridian plane by its transformation matrix (124), trimmed by a circle round the axis. The arc
|
||||
/// is only the part of the circle the cap needs; read as the whole circle, the revolution was a
|
||||
/// whole sphere twice over and the cap meshed as the full ball.
|
||||
/// A unit-cube-like box (10 × 20 × 30) made of six trimmed bilinear B-spline patches whose
|
||||
/// boundaries are lines: sewn into a closed solid.
|
||||
#[test]
|
||||
fn an_arc_revolved_about_its_centre_is_a_cap_not_a_ball() {
|
||||
let (r, polar) = (50.0f64, 30f64.to_radians());
|
||||
let (rim_r, rim_z) = (r * polar.sin(), r * polar.cos());
|
||||
let ents: Vec<(i64, i64, String, i64)> = vec![
|
||||
// 1: the meridian plane: local x stays x, local y becomes z.
|
||||
(124, 0, "1.,0.,0.,0.,0.,0.,-1.,0.,0.,1.,0.,0.".into(), 0),
|
||||
// 3: the axis, 5: the arc from the rim (60° in its plane) to the pole (90°).
|
||||
(110, 0, "0.,0.,0.,0.,0.,1.".into(), 0),
|
||||
(100, 0, format!("0.,0.,0.,{:?},{:?},0.,{r:?}", rim_r, rim_z), 1),
|
||||
// 7: the surface, 9: the rim (a full circle at the cap's height), 11: on the surface.
|
||||
(120, 0, format!("3,5,0.,{:?}", std::f64::consts::TAU), 0),
|
||||
(100, 0, format!("{rim_z:?},0.,0.,{rim_r:?},0.,{rim_r:?},0."), 0),
|
||||
(142, 0, "0,7,0,9,2".into(), 0),
|
||||
// 13: the cap.
|
||||
(144, 0, "7,1,0,11".into(), 0),
|
||||
];
|
||||
let imp = iges_import(&iges_file_placed(&ents)).unwrap();
|
||||
assert_eq!(imp.bodies.len(), 1, "{:?}", imp.warnings);
|
||||
let mesh = imp.bodies[0].body.tessellate(0.01).unwrap();
|
||||
let (mut lo, mut hi) = ([f64::MAX; 3], [f64::MIN; 3]);
|
||||
for p in &mesh.positions {
|
||||
for (k, x) in [p.x, p.y, p.z].into_iter().enumerate() {
|
||||
lo[k] = lo[k].min(x);
|
||||
hi[k] = hi[k].max(x);
|
||||
}
|
||||
}
|
||||
for k in 0..2 {
|
||||
assert!((lo[k] + rim_r).abs() < 0.1 && (hi[k] - rim_r).abs() < 0.1, "cap is {lo:?} .. {hi:?}");
|
||||
}
|
||||
assert!((lo[2] - rim_z).abs() < 0.1 && (hi[2] - r).abs() < 0.1, "cap is {lo:?} .. {hi:?}");
|
||||
// Area of a cap: 2π r h.
|
||||
let area = measure(&imp.bodies[0].body).unwrap().area;
|
||||
let cap = std::f64::consts::TAU * r * (r - rim_z);
|
||||
assert!(rel(area, cap) < 1e-3, "area {area} vs {cap}");
|
||||
}
|
||||
|
||||
/// An exported box inside a named group and nested subfigures, placed twice. The second
|
||||
/// placement composes its translation and scale with a directory transformation.
|
||||
fn assembly_file(form: i64, scale: f64) -> String {
|
||||
let body = box_solid(Vec3::ZERO, Vec3::new(2.0, 3.0, 4.0)).unwrap();
|
||||
let text = iges_export_bodies(&[ExportBody { name: "Body1".into(), body: &body, color: None }], &StepHeader::default()).unwrap();
|
||||
let f = parse(&text).unwrap();
|
||||
let mut ids: Vec<_> = f.des.keys().copied().collect();
|
||||
ids.sort_unstable();
|
||||
let solid = *ids.iter().find(|&&s| f.des[&s].typ == 186).unwrap();
|
||||
let mut transforms: HashMap<_, _> = f.des.iter().map(|(seq, d)| (*seq, d.xform)).collect();
|
||||
let mut ents: Vec<_> = ids
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(k, seq)| {
|
||||
assert_eq!(*seq, 2 * k + 1);
|
||||
let d = &f.des[seq];
|
||||
let p = f.params[seq]
|
||||
.iter()
|
||||
.skip(1)
|
||||
.map(|s| if s.is_empty() || num(s).is_some() { s.clone() } else { format!("{}H{s}", s.chars().count()) })
|
||||
.collect::<Vec<_>>()
|
||||
.join(",");
|
||||
(d.typ, d.form, p)
|
||||
})
|
||||
.collect();
|
||||
let definition = 2 * ents.len() + 1;
|
||||
ents.push((308, 0, format!("0,8HLead rod,1,{solid}")));
|
||||
let first = 2 * ents.len() + 1;
|
||||
ents.push((408, 0, format!("{definition},10.,0.,0.,1.")));
|
||||
let rotation = 2 * ents.len() + 1;
|
||||
ents.push((124, 0, "0.,-1.,0.,100.,1.,0.,0.,0.,0.,0.,1.,0.".into()));
|
||||
let second = 2 * ents.len() + 1;
|
||||
ents.push((408, 0, format!("{definition},0.,20.,0.,{scale}")));
|
||||
transforms.insert(second, rotation as i64);
|
||||
let frame = 2 * ents.len() + 1;
|
||||
ents.push((308, 0, format!("1,5HFrame,2,{first},{second}")));
|
||||
let property = 2 * ents.len() + 1;
|
||||
ents.push((406, 15, "1,6HMotion".into()));
|
||||
ents.push((402, form, format!("1,{frame},0,1,{property}")));
|
||||
iges_file(&ents)
|
||||
.lines()
|
||||
.map(|line| {
|
||||
if line.as_bytes()[72] != b'D' {
|
||||
return line.to_string();
|
||||
}
|
||||
let seq: usize = line[73..80].trim().parse().unwrap();
|
||||
match transforms.get(&seq) {
|
||||
Some(xf) => format!("{}{:>8}{}", &line[..48], xf, &line[56..]),
|
||||
None => line.to_string(),
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn groups_and_subfigure_instances_keep_names_structure_and_placements() {
|
||||
for (form, scale) in [(1, 1.0), (7, 2.0), (14, 1.0), (15, 2.0)] {
|
||||
let imp = iges_import(&assembly_file(form, scale)).unwrap();
|
||||
assert!(imp.warnings.is_empty(), "{:?}", imp.warnings);
|
||||
assert_eq!(imp.bodies.len(), 2);
|
||||
assert_eq!(imp.tree.len(), 1);
|
||||
let motion = &imp.tree[0].children[0];
|
||||
assert_eq!(motion.name, "Motion");
|
||||
let frame = &motion.children[0];
|
||||
assert_eq!(frame.name, "Frame");
|
||||
assert_eq!(frame.children.len(), 2);
|
||||
assert!(frame.children.iter().all(|n| n.name == "Lead rod"));
|
||||
assert!(imp.bodies.iter().all(|b| b.path == ["Import", "Motion", "Frame", "Lead rod"]));
|
||||
assert_eq!(imp.bodies[0].source_item, imp.bodies[1].source_item);
|
||||
let a = measure(&imp.bodies[0].body).unwrap();
|
||||
let b = measure(&imp.bodies[1].body).unwrap();
|
||||
assert!(rel(a.volume, 24.0) < 1e-6 && rel(b.volume, 24.0 * scale.powi(3)) < 1e-6);
|
||||
assert!(a.bbox.min.dist(Vec3::new(10.0, 0.0, 0.0)) < 1e-6 && a.bbox.max.dist(Vec3::new(12.0, 3.0, 4.0)) < 1e-6);
|
||||
assert!(b.bbox.min.dist(Vec3::new(80.0 - 3.0 * scale, 0.0, 0.0)) < 1e-6);
|
||||
assert!(b.bbox.max.dist(Vec3::new(80.0, 2.0 * scale, 4.0 * scale)) < 1e-6);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_assembly_references_and_counts_fail_before_geometry() {
|
||||
for (params, message) in [
|
||||
("0,4HLoop,1,1".into(), "cyclic"),
|
||||
("0,4HPart,1,999".into(), "missing entity"),
|
||||
("0,4HPart,-1".into(), "negative IGES group size"),
|
||||
(format!("0,4HPart,{}", MAX_LIST + 1), "work limit"),
|
||||
] {
|
||||
let error = iges_import(&iges_file(&[(308, 0, params)])).unwrap_err();
|
||||
assert!(matches!(&error, crate::KernelError::Invalid(text) if text.contains(message)), "{error}");
|
||||
}
|
||||
let mut chain = Vec::new();
|
||||
for k in 0..=MAX_DEPTH {
|
||||
chain.push((308, 0, if k == MAX_DEPTH { "0,4HPart,0".into() } else { format!("0,4HPart,1,{}", 2 * k + 3) }));
|
||||
}
|
||||
let error = iges_import(&iges_file(&chain)).unwrap_err();
|
||||
assert!(matches!(&error, crate::KernelError::Invalid(text) if text.contains("nesting is too deep")), "{error}");
|
||||
let members = "1,".repeat(100_000);
|
||||
let many = [(308, 0, "0,4HPart,0".into()), (308, 0, format!("1,5HFrame,100001,{members}1"))];
|
||||
let error = iges_import(&iges_file(&many)).unwrap_err();
|
||||
assert!(matches!(&error, crate::KernelError::Invalid(text) if text.contains("too many IGES assembly placements")), "{error}");
|
||||
}
|
||||
|
||||
/// Six trimmed bilinear patches with line boundaries, forming a 10 × 20 × 30 box.
|
||||
fn trimmed_box(ents: &mut Vec<(i64, i64, String)>, x: f64) -> Vec<usize> {
|
||||
let c = |i: usize| -> [f64; 3] {
|
||||
[x + if i & 1 != 0 { 10.0 } else { 0.0 }, if i & 2 != 0 { 20.0 } else { 0.0 }, if i & 4 != 0 { 30.0 } else { 0.0 }]
|
||||
};
|
||||
fn trimmed_surfaces_sew_into_a_solid() {
|
||||
let c =
|
||||
|i: usize| -> [f64; 3] { [if i & 1 != 0 { 10.0 } else { 0.0 }, if i & 2 != 0 { 20.0 } else { 0.0 }, if i & 4 != 0 { 30.0 } else { 0.0 }] };
|
||||
// Faces as corner quads (counter-clockwise seen from outside).
|
||||
let quads = [[0, 2, 3, 1], [4, 5, 7, 6], [0, 1, 5, 4], [2, 6, 7, 3], [0, 4, 6, 2], [1, 3, 7, 5]];
|
||||
let mut faces = Vec::new();
|
||||
let mut ents: Vec<(i64, i64, String)> = Vec::new();
|
||||
let fmt = |p: [f64; 3]| format!("{:?},{:?},{:?}", p[0], p[1], p[2]);
|
||||
for q in quads {
|
||||
let (a, b, cc, d) = (c(q[0]), c(q[1]), c(q[2]), c(q[3]));
|
||||
@@ -283,15 +134,7 @@ fn trimmed_box(ents: &mut Vec<(i64, i64, String)>, x: f64) -> Vec<usize> {
|
||||
ents.push((142, 0, format!("0,{s_de},0,{comp},2")));
|
||||
let cos = 2 * ents.len() - 1;
|
||||
ents.push((144, 0, format!("{s_de},1,0,{cos}")));
|
||||
faces.push(2 * ents.len() - 1);
|
||||
}
|
||||
faces
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trimmed_surfaces_sew_into_a_solid() {
|
||||
let mut ents = Vec::new();
|
||||
trimmed_box(&mut ents, 0.0);
|
||||
let imp = iges_import(&iges_file(&ents)).unwrap();
|
||||
assert!(imp.warnings.is_empty(), "{:?}", imp.warnings);
|
||||
assert!(imp.bodies[0].closed);
|
||||
@@ -299,25 +142,6 @@ fn trimmed_surfaces_sew_into_a_solid() {
|
||||
assert!(rel(m.volume, 6000.0) < 1e-6 && rel(m.area, 2200.0) < 1e-6, "{} {}", m.volume, m.area);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn surfaces_in_separate_groups_remain_separate_parts() {
|
||||
let mut ents = Vec::new();
|
||||
for (name, x) in [("Left", 0.0), ("Right", 100.0)] {
|
||||
let faces = trimmed_box(&mut ents, x);
|
||||
let members = faces.iter().map(|s| s.to_string()).collect::<Vec<_>>().join(",");
|
||||
ents.push((308, 0, format!("0,{}H{name},{},{members}", name.len(), faces.len())));
|
||||
}
|
||||
let imp = iges_import(&iges_file(&ents)).unwrap();
|
||||
assert!(imp.warnings.is_empty(), "{:?}", imp.warnings);
|
||||
assert_eq!(imp.bodies.len(), 2);
|
||||
assert_eq!(imp.tree[0].children.iter().map(|n| n.name.as_str()).collect::<Vec<_>>(), ["Left", "Right"]);
|
||||
for (body, x) in imp.bodies.iter().zip([0.0, 100.0]) {
|
||||
let m = measure(&body.body).unwrap();
|
||||
assert!(body.closed && rel(m.volume, 6000.0) < 1e-6 && rel(m.area, 2200.0) < 1e-6);
|
||||
assert!(m.bbox.min.dist(Vec3::new(x, 0.0, 0.0)) < 1e-6 && m.bbox.max.dist(Vec3::new(x + 10.0, 20.0, 30.0)) < 1e-6);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_drill_point_round_trips_through_iges() {
|
||||
// A blind hole with a cone tip: the tip's face closes at its apex (its seam runs out to the
|
||||
@@ -385,127 +209,3 @@ fn directory_entries_cannot_share_their_way_past_the_file_size() {
|
||||
assert!(error.contains("parameter data is too large"), "{error}");
|
||||
assert!(t.elapsed() < std::time::Duration::from_secs(10), "took {:?}", t.elapsed());
|
||||
}
|
||||
|
||||
/// A curve on a surface (142) for a trimmed patch: model-space lines through `corners` with the
|
||||
/// pieces `reversed` written end to start (as some exporters write composite trim curves), and
|
||||
/// the same loop in the patch's parameter space through `uv`. Returns the 142's pointer.
|
||||
fn trim_loop(ents: &mut Vec<(i64, i64, String)>, surface: usize, corners: &[[f64; 3]], uv: &[[f64; 2]], reversed: &[usize]) -> usize {
|
||||
let fmt = |p: [f64; 3]| format!("{:?},{:?},{:?}", p[0], p[1], p[2]);
|
||||
let mut model = Vec::new();
|
||||
let mut param = Vec::new();
|
||||
for k in 0..corners.len() {
|
||||
let (p0, p1) = (corners[k], corners[(k + 1) % corners.len()]);
|
||||
let (p0, p1) = if reversed.contains(&k) { (p1, p0) } else { (p0, p1) };
|
||||
ents.push((110, 0, format!("{},{}", fmt(p0), fmt(p1))));
|
||||
model.push(2 * ents.len() - 1);
|
||||
let (q0, q1) = (uv[k], uv[(k + 1) % uv.len()]);
|
||||
ents.push((110, 0, format!("{},{}", fmt([q0[0], q0[1], 0.0]), fmt([q1[0], q1[1], 0.0]))));
|
||||
param.push(2 * ents.len() - 1);
|
||||
}
|
||||
let list = |v: &[usize]| v.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(",");
|
||||
ents.push((102, 0, format!("{},{}", model.len(), list(&model))));
|
||||
let c = 2 * ents.len() - 1;
|
||||
ents.push((102, 0, format!("{},{}", param.len(), list(¶m))));
|
||||
let b = 2 * ents.len() - 1;
|
||||
// Created by projection, preferring the parameter-space curve (PREF 1).
|
||||
ents.push((142, 0, format!("0,{surface},{b},{c},1")));
|
||||
2 * ents.len() - 1
|
||||
}
|
||||
|
||||
/// A bilinear B-spline patch through corners `a` (u, v = 0), `b` (u = 1), `c` (u, v = 1) and
|
||||
/// `d` (v = 1).
|
||||
fn bilinear_patch(a: [f64; 3], b: [f64; 3], c: [f64; 3], d: [f64; 3]) -> (i64, i64, String) {
|
||||
let fmt = |p: [f64; 3]| format!("{:?},{:?},{:?}", p[0], p[1], p[2]);
|
||||
(128, 0, format!("1,1,1,1,0,0,1,0,0,0.,0.,1.,1.,0.,0.,1.,1.,1.,1.,1.,1.,{},{},{},{},0.,1.,0.,1.", fmt(a), fmt(b), fmt(d), fmt(c)))
|
||||
}
|
||||
|
||||
/// The box of `trimmed_surfaces_sew_into_a_solid` with some pieces of every trim curve written
|
||||
/// end to start (the first piece on half the faces): each face's loop still closes and the box
|
||||
/// is a solid.
|
||||
#[test]
|
||||
fn trim_curves_with_reversed_pieces_still_close_their_faces() {
|
||||
let c =
|
||||
|i: usize| -> [f64; 3] { [if i & 1 != 0 { 10.0 } else { 0.0 }, if i & 2 != 0 { 20.0 } else { 0.0 }, if i & 4 != 0 { 30.0 } else { 0.0 }] };
|
||||
let quads = [[0, 2, 3, 1], [4, 5, 7, 6], [0, 1, 5, 4], [2, 6, 7, 3], [0, 4, 6, 2], [1, 3, 7, 5]];
|
||||
let mut ents: Vec<(i64, i64, String)> = Vec::new();
|
||||
for (fi, q) in quads.iter().enumerate() {
|
||||
let corners = q.map(c);
|
||||
ents.push(bilinear_patch(corners[0], corners[1], corners[2], corners[3]));
|
||||
let surface = 2 * ents.len() - 1;
|
||||
let reversed: &[usize] = if fi % 2 == 0 { &[0, 2] } else { &[1, 3] };
|
||||
let cos = trim_loop(&mut ents, surface, &corners, &[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]], reversed);
|
||||
ents.push((144, 0, format!("{surface},1,0,{cos}")));
|
||||
}
|
||||
let imp = iges_import(&iges_file(&ents)).unwrap();
|
||||
assert!(imp.warnings.is_empty(), "{:?}", imp.warnings);
|
||||
assert!(imp.bodies[0].closed);
|
||||
let m = measure(&imp.bodies[0].body).unwrap();
|
||||
assert!(rel(m.volume, 6000.0) < 1e-6 && rel(m.area, 2200.0) < 1e-6, "{} {}", m.volume, m.area);
|
||||
}
|
||||
|
||||
/// A plate with a square hole whose trim curve starts with a reversed piece: where the
|
||||
/// parameter-space curve starts decides which way the hole runs, so it stays a hole.
|
||||
#[test]
|
||||
fn a_hole_whose_first_trim_piece_is_reversed_stays_a_hole() {
|
||||
let mut ents: Vec<(i64, i64, String)> = vec![bilinear_patch([0.0; 3], [10.0, 0.0, 0.0], [10.0, 10.0, 0.0], [0.0, 10.0, 0.0])];
|
||||
let outer = trim_loop(
|
||||
&mut ents,
|
||||
1,
|
||||
&[[0.0, 0.0, 0.0], [10.0, 0.0, 0.0], [10.0, 10.0, 0.0], [0.0, 10.0, 0.0]],
|
||||
&[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]],
|
||||
&[],
|
||||
);
|
||||
// Clockwise about the patch's normal, as a hole runs.
|
||||
let hole = trim_loop(
|
||||
&mut ents,
|
||||
1,
|
||||
&[[3.0, 3.0, 0.0], [3.0, 7.0, 0.0], [7.0, 7.0, 0.0], [7.0, 3.0, 0.0]],
|
||||
&[[0.3, 0.3], [0.3, 0.7], [0.7, 0.7], [0.7, 0.3]],
|
||||
&[0],
|
||||
);
|
||||
ents.push((144, 0, format!("1,1,1,{outer},{hole}")));
|
||||
let imp = iges_import(&iges_file(&ents)).unwrap();
|
||||
assert_eq!(imp.bodies.len(), 1);
|
||||
assert!(!imp.warnings.iter().any(|w| w.contains("not read") || w.contains("face #")), "{:?}", imp.warnings);
|
||||
let m = measure(&imp.bodies[0].body).unwrap();
|
||||
assert!(rel(m.area, 84.0) < 1e-6, "area {}", m.area);
|
||||
}
|
||||
|
||||
/// The box of `trimmed_surfaces_sew_into_a_solid` with one edge written as a B-spline (126)
|
||||
/// over a knot span of 1e-7 or less, as some exporters write short curves: the STEP side read
|
||||
/// that span as a single value and refused the curve, and both faces it bounds were lost.
|
||||
#[test]
|
||||
fn a_curve_over_a_tiny_knot_span_still_bounds_its_faces() {
|
||||
let c =
|
||||
|i: usize| -> [f64; 3] { [if i & 1 != 0 { 10.0 } else { 0.0 }, if i & 2 != 0 { 20.0 } else { 0.0 }, if i & 4 != 0 { 30.0 } else { 0.0 }] };
|
||||
let quads = [[0, 2, 3, 1], [4, 5, 7, 6], [0, 1, 5, 4], [2, 6, 7, 3], [0, 4, 6, 2], [1, 3, 7, 5]];
|
||||
let fmt = |p: [f64; 3]| format!("{:?},{:?},{:?}", p[0], p[1], p[2]);
|
||||
for span in [1e-7f64, 1e-9, 1e-13] {
|
||||
let mut ents: Vec<(i64, i64, String)> = Vec::new();
|
||||
for (fi, q) in quads.iter().enumerate() {
|
||||
let (a, b, cc, d) = (c(q[0]), c(q[1]), c(q[2]), c(q[3]));
|
||||
let surf = format!("1,1,1,1,0,0,1,0,0,0.,0.,1.,1.,0.,0.,1.,1.,1.,1.,1.,1.,{},{},{},{},0.,1.,0.,1.", fmt(a), fmt(b), fmt(d), fmt(cc));
|
||||
ents.push((128, 0, surf));
|
||||
let s_de = 2 * ents.len() - 1;
|
||||
let mut lines = Vec::new();
|
||||
for (k, (p0, p1)) in [(a, b), (b, cc), (cc, d), (d, a)].into_iter().enumerate() {
|
||||
if fi == 0 && k == 0 {
|
||||
ents.push((126, 0, format!("1,1,0,0,1,0,0.,0.,{span:E},{span:E},1.,1.,{},{},0.,{span:E},0.,0.,1.", fmt(p0), fmt(p1))));
|
||||
} else {
|
||||
ents.push((110, 0, format!("{},{}", fmt(p0), fmt(p1))));
|
||||
}
|
||||
lines.push(2 * ents.len() - 1);
|
||||
}
|
||||
ents.push((102, 0, format!("4,{}", lines.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(","))));
|
||||
let comp = 2 * ents.len() - 1;
|
||||
ents.push((142, 0, format!("0,{s_de},0,{comp},2")));
|
||||
let cos = 2 * ents.len() - 1;
|
||||
ents.push((144, 0, format!("{s_de},1,0,{cos}")));
|
||||
}
|
||||
let imp = iges_import(&iges_file(&ents)).unwrap();
|
||||
assert!(imp.warnings.is_empty(), "span {span}: {:?}", imp.warnings);
|
||||
assert!(imp.bodies[0].closed, "span {span}");
|
||||
let m = measure(&imp.bodies[0].body).unwrap();
|
||||
assert!(rel(m.volume, 6000.0) < 1e-6 && rel(m.area, 2200.0) < 1e-6, "span {span}: {} {}", m.volume, m.area);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -153,7 +153,6 @@ mod tspline;
|
||||
#[cfg(test)]
|
||||
mod untouched_faces_tests;
|
||||
pub mod watch;
|
||||
mod whole_face;
|
||||
|
||||
pub use blend::{ChamferSide, chamfer, chamfer_sides, fillet, fillet_each, fillet_g2, fillet_g2_corners, fillet_max, fillet_max_each};
|
||||
pub use blend_corner::fillet_radii;
|
||||
@@ -221,7 +220,6 @@ pub use sweep_path::{RailFit, SweepControl, SweepOrientation, sweep_path, sweep_
|
||||
pub use topo::{CylinderFace, cylinder_end_at, cylinder_face, cylinder_face_at};
|
||||
pub use topo::{TopoCounts, merged_topology, seam_flags};
|
||||
pub use tspline::tspline_sheet;
|
||||
pub use whole_face::{WholeFace, cut_takes_only_the_face, cut_tool, face_prism, matching_face};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
|
||||
pub enum KernelError {
|
||||
|
||||
@@ -85,13 +85,9 @@ impl NumberedLoop {
|
||||
NumberedLoop { lp: pieces, from }
|
||||
}
|
||||
|
||||
/// Re-split into exactly `n` segments, other loops split their longest segments in half. A
|
||||
/// full circle is split once round (one turn, every arc a positive sweep) to follow a lead
|
||||
/// loop: at the lead's vertex directions `angles` when they go round in order (counter-
|
||||
/// clockwise, or clockwise when `clockwise`), otherwise from the first of them at the lead's
|
||||
/// perimeter `fractions` (the share of the lead's length before each vertex; evenly when
|
||||
/// those are unusable).
|
||||
pub(crate) fn resample(&self, n: usize, angles: &[f64], fractions: &[f64], clockwise: bool) -> NumberedLoop {
|
||||
/// Re-split into exactly `n` segments: a full circle gets breaks at `angles` (or evenly),
|
||||
/// other loops split their longest segments in half.
|
||||
pub(crate) fn resample(&self, n: usize, angles: &[f64]) -> NumberedLoop {
|
||||
let lp = &self.lp;
|
||||
let circle = lp.segs.iter().all(|s| matches!(s, Seg2::Arc { .. }))
|
||||
&& lp.segs.windows(2).all(|w| match (w.first(), w.get(1)) {
|
||||
@@ -100,15 +96,22 @@ impl NumberedLoop {
|
||||
}
|
||||
_ => false,
|
||||
});
|
||||
if circle
|
||||
&& n > 0
|
||||
&& let Some(Seg2::Arc { center, radius, .. }) = lp.segs.first().copied()
|
||||
{
|
||||
let a = circle_breaks(n, angles, fractions, clockwise);
|
||||
let segs: Vec<Seg2> = (0..a.len())
|
||||
if circle && let Some(Seg2::Arc { center, radius, .. }) = lp.segs.first().copied() {
|
||||
let mut a: Vec<f64> =
|
||||
if angles.len() == n { angles.to_vec() } else { (0..n).map(|i| std::f64::consts::TAU * i as f64 / n as f64).collect() };
|
||||
// Keep the given order but make them increase.
|
||||
for i in 1..a.len() {
|
||||
let Some(prev) = a.get(i - 1).copied() else { continue };
|
||||
if let Some(x) = a.get_mut(i) {
|
||||
while *x <= prev {
|
||||
*x += std::f64::consts::TAU;
|
||||
}
|
||||
}
|
||||
}
|
||||
let segs: Vec<Seg2> = (0..n)
|
||||
.filter_map(|i| {
|
||||
let s = *a.get(i)?;
|
||||
let e = if i + 1 < a.len() { *a.get(i + 1)? } else { a.first()? + std::f64::consts::TAU };
|
||||
let e = if i + 1 < n { *a.get(i + 1)? } else { a.first()? + std::f64::consts::TAU };
|
||||
Some(Seg2::Arc { center, radius, start: s, sweep: e - s })
|
||||
})
|
||||
.collect();
|
||||
@@ -187,65 +190,6 @@ impl NumberedRegion {
|
||||
}
|
||||
}
|
||||
|
||||
/// The smallest arc a circle is split into (radians).
|
||||
const MIN_SWEEP: f64 = 1e-9;
|
||||
|
||||
/// `n` increasing break angles of one turn round a circle (each step and the closing step back
|
||||
/// to the first, one turn on, positive) for a circle following a lead loop: `angles` (the lead's
|
||||
/// vertex directions) when they go round once in order in the lead's direction (counter-clockwise,
|
||||
/// or clockwise when `clockwise`), otherwise from the first of them at the lead's perimeter
|
||||
/// `fractions`, or evenly. A non-star-shaped lead's directions turn back on themselves: forcing
|
||||
/// them to increase wound the circle round many times (#2570).
|
||||
fn circle_breaks(n: usize, angles: &[f64], fractions: &[f64], clockwise: bool) -> Vec<f64> {
|
||||
use std::f64::consts::TAU;
|
||||
let sign = if clockwise { -1.0 } else { 1.0 };
|
||||
// Angles measured in the lead's direction of travel.
|
||||
let along: Vec<f64> = angles.iter().map(|a| sign * a).collect();
|
||||
let run = (along.len() == n).then(|| one_turn(&along)).flatten().unwrap_or_else(|| {
|
||||
let start = along.first().copied().filter(|a| a.is_finite()).unwrap_or(0.0);
|
||||
let even = || (0..n).map(|i| i as f64 / n as f64).collect::<Vec<f64>>();
|
||||
let f = if usable_fractions(n, fractions) { fractions.to_vec() } else { even() };
|
||||
f.iter().map(|f| start + TAU * f).collect()
|
||||
});
|
||||
let mut breaks: Vec<f64> = run.into_iter().map(|a| sign * a).collect();
|
||||
if clockwise {
|
||||
breaks.reverse();
|
||||
}
|
||||
breaks
|
||||
}
|
||||
|
||||
/// `along` unwrapped into one increasing turn (each step the shortest positive one), or `None`
|
||||
/// when they do not go round once in order.
|
||||
fn one_turn(along: &[f64]) -> Option<Vec<f64>> {
|
||||
let mut out: Vec<f64> = Vec::with_capacity(along.len());
|
||||
for &x in along {
|
||||
if !x.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let next = match out.last() {
|
||||
Some(&prev) => {
|
||||
let step = (x - prev).rem_euclid(std::f64::consts::TAU);
|
||||
if step <= MIN_SWEEP {
|
||||
return None;
|
||||
}
|
||||
prev + step
|
||||
}
|
||||
None => x,
|
||||
};
|
||||
out.push(next);
|
||||
}
|
||||
let (first, last) = (*out.first()?, *out.last()?);
|
||||
(last - first < std::f64::consts::TAU - MIN_SWEEP).then_some(out)
|
||||
}
|
||||
|
||||
/// `fractions` are `n` finite, strictly increasing shares of a turn from 0, all under one.
|
||||
fn usable_fractions(n: usize, fractions: &[f64]) -> bool {
|
||||
fractions.len() == n
|
||||
&& fractions.first().is_some_and(|f| f.abs() < MIN_SWEEP)
|
||||
&& fractions.windows(2).all(|w| matches!(w, [a, b] if b - a > MIN_SWEEP))
|
||||
&& fractions.last().is_some_and(|f| f.is_finite() && *f < 1.0 - MIN_SWEEP)
|
||||
}
|
||||
|
||||
/// Every number of `sets`, once each, in order.
|
||||
fn union<'a>(sets: impl IntoIterator<Item = &'a [usize]>) -> Vec<usize> {
|
||||
sets.into_iter().flatten().copied().collect::<BTreeSet<usize>>().into_iter().collect()
|
||||
|
||||
@@ -796,7 +796,7 @@ fn unsupported_shell(m: &str) -> KernelError {
|
||||
KernelError::Failed(format!("not supported yet: {m}"))
|
||||
}
|
||||
|
||||
pub(crate) fn point_tri(p: Vec3, a: Vec3, b: Vec3, c: Vec3) -> f64 {
|
||||
fn point_tri(p: Vec3, a: Vec3, b: Vec3, c: Vec3) -> f64 {
|
||||
let n = (b - a).cross(c - a);
|
||||
let Some(nn) = n.normalized() else { return f64::INFINITY };
|
||||
let h = (p - a).dot(nn);
|
||||
|
||||
@@ -53,63 +53,6 @@ fn rid(p: Option<&Param>, what: &str) -> R<u64> {
|
||||
/// A contractible outer loop whose winding opposes the surface's parameter normal.
|
||||
/// Samples follow the wire through periodic seams; a loop that winds around a surface is
|
||||
/// not a disk in parameter space and must retain the file's sense.
|
||||
/// The point of a cone (a surface revolved from a line that meets its axis) when `ring`, a
|
||||
/// face's only loop, goes once round the axis without touching it: the face then reaches the
|
||||
/// point. `None` for any other surface or loop.
|
||||
fn enclosed_apex(surface: &mt::Surface, ring: &mt::Wire, tol: f64) -> Option<mt::Point3> {
|
||||
use mt::Transform as _;
|
||||
let mt::Surface::RevolutedCurve(proc) = surface else { return None };
|
||||
let rc = proc.entity();
|
||||
let mt::Curve::Line(line) = rc.entity_curve() else { return None };
|
||||
let (o, axis) = (rc.origin(), rc.axis().normalize());
|
||||
// The rotation applied to the revolved surface, applied to its axis and profile too.
|
||||
let m = proc.transform();
|
||||
let (o, axis) = (m.transform_point(o), m.transform_vector(axis).normalize());
|
||||
let (p0, p1) = (m.transform_point(line.0), m.transform_point(line.1));
|
||||
let radius = |p: mt::Point3| (p - o).cross(axis).magnitude();
|
||||
let (r0, r1) = (radius(p0), radius(p1));
|
||||
if !((r0 - r1).abs() > 1e-9 * (r0 + r1)) {
|
||||
return None;
|
||||
}
|
||||
let apex = p0 + (p1 - p0) * (r0 / (r0 - r1));
|
||||
if !(radius(apex) <= tol.max(1e-9) * 10.0) {
|
||||
return None;
|
||||
}
|
||||
// Once round the axis, staying clear of it.
|
||||
let x = (p0 - o) - axis * (p0 - o).dot(axis);
|
||||
let x = if x.magnitude() > tol { x.normalize() } else { return None };
|
||||
let y = axis.cross(x);
|
||||
let mut turned = 0.0;
|
||||
let mut last: Option<f64> = None;
|
||||
let mut first: Option<f64> = None;
|
||||
for edge in ring.edge_iter() {
|
||||
let c = edge.oriented_curve();
|
||||
let (t0, t1) = c.range_tuple();
|
||||
for k in 0..16 {
|
||||
let q = c.subs(t0 + (t1 - t0) * f64::from(k) / 16.0);
|
||||
if radius(q) <= tol {
|
||||
return None;
|
||||
}
|
||||
let d = q - o;
|
||||
let ang = d.dot(y).atan2(d.dot(x));
|
||||
if let Some(l) = last {
|
||||
let mut step = ang - l;
|
||||
step -= (step / std::f64::consts::TAU).round() * std::f64::consts::TAU;
|
||||
turned += step;
|
||||
} else {
|
||||
first = Some(ang);
|
||||
}
|
||||
last = Some(ang);
|
||||
}
|
||||
}
|
||||
if let (Some(l), Some(f)) = (last, first) {
|
||||
let mut step = f - l;
|
||||
step -= (step / std::f64::consts::TAU).round() * std::f64::consts::TAU;
|
||||
turned += step;
|
||||
}
|
||||
((turned.abs() - std::f64::consts::TAU).abs() < 0.1).then_some(apex)
|
||||
}
|
||||
|
||||
fn reversed_outer(surface: &mt::Surface, wire: &mt::Wire, tol: f64) -> bool {
|
||||
if let mt::Surface::RevolutedCurve(proc) = surface {
|
||||
let rc = proc.entity();
|
||||
@@ -378,35 +321,6 @@ impl Builder {
|
||||
surface = guard("step surface orientation", || geom::surface(cx, sid, &extent, &seam, !sense, 0).map_err(crate::KernelError::Failed))
|
||||
.map_err(|e| e.to_string())?;
|
||||
}
|
||||
// A cone face bounded only by a ring round its axis (no vertex at the point, or a
|
||||
// VERTEX_LOOP there, which has no edges) covers the cone up to its point. Its surface
|
||||
// was spanned over the ring alone, a sliver at the base; it is spanned to the apex,
|
||||
// and the ring is joined to the apex by a seam line out and back, as a cone with a
|
||||
// seam is written.
|
||||
let (mut wires, mut surface) = (wires, surface);
|
||||
if e.name() != "FACE"
|
||||
&& seam.is_empty()
|
||||
&& let [ring] = wires.as_slice()
|
||||
&& let Some(apex) = enclosed_apex(&surface, ring, cx.tol)
|
||||
&& let Some(first) = ring.edge_iter().next()
|
||||
{
|
||||
let v = first.front().clone();
|
||||
let a = mt::Vertex::new(apex);
|
||||
let line = mt::Edge::new_unchecked(&v, &a, mt::Curve::Line(mt::Line(v.point(), apex)));
|
||||
let mut to_apex = extent.clone();
|
||||
to_apex.push(apex);
|
||||
let seam_line = [v.point(), apex];
|
||||
let sid = rid(p.get(2), "face geometry")?;
|
||||
let sense = p.get(3).and_then(Param::as_bool).unwrap_or(true);
|
||||
let spanned =
|
||||
guard("step cone to its point", || geom::surface(cx, sid, &to_apex, &seam_line, sense, 0).map_err(crate::KernelError::Failed))
|
||||
.map_err(|e| e.to_string())?;
|
||||
let mut edges: Vec<mt::Edge> = ring.edge_iter().cloned().collect();
|
||||
edges.push(line.clone());
|
||||
edges.push(line.inverse());
|
||||
wires = vec![edges.into()];
|
||||
surface = spanned;
|
||||
}
|
||||
// Loops on a surface of revolution start away from the axis: a pole (cone apex, sphere
|
||||
// pole) has no definite rotation parameter, and the mesher takes the first point's
|
||||
// parameter as the anchor for the rest of the loop.
|
||||
@@ -641,22 +555,5 @@ pub(crate) fn read_item(cx: &Ctx, id: u64) -> R<BrepOut> {
|
||||
if checked.is_err() {
|
||||
closed = false;
|
||||
}
|
||||
// A void's faces face into the cavity, out of the material: it encloses volume of the
|
||||
// opposite sign to the outer shell. The ORIENTED_CLOSED_SHELL flag alone doesn't say so:
|
||||
// some exporters write .F. over a shell already facing into the cavity (#3730), others .T.
|
||||
// A void enclosing volume of the outer shell's sign is turned inside out.
|
||||
if e.name() == "BREP_WITH_VOIDS"
|
||||
&& checked.is_ok()
|
||||
&& let Some((outer, voids)) = shells.split_first_mut()
|
||||
&& let Some(outside) = crate::body::shell_volume(outer)
|
||||
{
|
||||
for void in voids {
|
||||
if crate::body::shell_volume(void).is_some_and(|v| v * outside > 0.0) {
|
||||
for face in void.face_iter_mut() {
|
||||
face.invert();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(BrepOut { solid: mt::Solid::new_unchecked(shells), failed, closed, file_faces, face_origin })
|
||||
}
|
||||
|
||||
@@ -236,40 +236,3 @@ fn hostile_conics_never_panic() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A cone to a point written with no vertex at its point (#258): the cone face's only loop is
|
||||
/// its base circle, or that circle and a VERTEX_LOOP at the point, which has no edges. It was
|
||||
/// read as a sliver at the base and the solid came in as a flat disc; the face reaches the
|
||||
/// point now.
|
||||
#[test]
|
||||
fn a_cone_bounded_only_by_its_base_circle_reaches_its_point() {
|
||||
let (r, h) = (6.0f64, 15.0f64);
|
||||
for apex_loop in [false, true] {
|
||||
let mut t = String::from(HEAD);
|
||||
t += "#1=CARTESIAN_POINT('',(0.,0.,0.));\n#2=DIRECTION('',(0.,0.,-1.));\n#3=DIRECTION('',(1.,0.,0.));\n#4=AXIS2_PLACEMENT_3D('',#1,#2,#3);\n";
|
||||
t += &format!("#5=CONICAL_SURFACE('',#4,{r:.1},{:.15});\n", (r / h).atan());
|
||||
t += "#6=DIRECTION('',(0.,0.,1.));\n#7=AXIS2_PLACEMENT_3D('',#1,#6,#3);\n#8=PLANE('',#7);\n";
|
||||
t += &format!("#9=CIRCLE('',#7,{r:.1});\n#10=CARTESIAN_POINT('',({r:.1},0.,0.));\n#11=VERTEX_POINT('',#10);\n");
|
||||
t += "#12=EDGE_CURVE('',#11,#11,#9,.T.);\n";
|
||||
t += "#20=ORIENTED_EDGE('',*,*,#12,.F.);\n#21=EDGE_LOOP('',(#20));\n#22=FACE_OUTER_BOUND('',#21,.T.);\n#23=ADVANCED_FACE('',(#22),#8,.F.);\n";
|
||||
t += "#30=ORIENTED_EDGE('',*,*,#12,.T.);\n#31=EDGE_LOOP('',(#30));\n#32=FACE_OUTER_BOUND('',#31,.T.);\n";
|
||||
if apex_loop {
|
||||
t += &format!(
|
||||
"#33=CARTESIAN_POINT('',(0.,0.,{h:.1}));\n#34=VERTEX_POINT('',#33);\n#35=VERTEX_LOOP('',#34);\n#36=FACE_BOUND('',#35,.T.);\n"
|
||||
);
|
||||
t += "#37=ADVANCED_FACE('',(#32,#36),#5,.T.);\n";
|
||||
} else {
|
||||
t += "#37=ADVANCED_FACE('',(#32),#5,.T.);\n";
|
||||
}
|
||||
t += "#80=CLOSED_SHELL('',(#23,#37));\n#81=MANIFOLD_SOLID_BREP('Cone',#80);\n";
|
||||
t += CONTEXT;
|
||||
t += TAIL;
|
||||
let imp = step_import(&t).unwrap();
|
||||
let body = &imp.bodies[0].body;
|
||||
let m = measure(body).unwrap();
|
||||
let exact = PI * r * r * h / 3.0;
|
||||
assert!(rel(m.volume, exact) < 2e-3, "vertex loop {apex_loop}: volume {} vs {exact}", m.volume);
|
||||
let top = body.tessellate(0.01).unwrap().positions.iter().map(|p| p.z).fold(f64::MIN, f64::max);
|
||||
assert!((top - h).abs() < 1e-6, "vertex loop {apex_loop}: reaches z = {top}, not {h}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -101,7 +101,7 @@ pub(crate) fn point(cx: &Ctx, id: u64) -> R<mt::Point3> {
|
||||
Ok(mt::Point3::new(g(0)?, g(1)?, g(2)?) * cx.len)
|
||||
}
|
||||
|
||||
pub(super) fn direction(cx: &Ctx, id: u64) -> R<mt::Vector3> {
|
||||
fn direction(cx: &Ctx, id: u64) -> R<mt::Vector3> {
|
||||
let e = entity(cx, id)?;
|
||||
if e.name() != "DIRECTION" {
|
||||
return Err(format!("#{id}: expected DIRECTION, found {}", e.name()));
|
||||
|
||||
@@ -562,39 +562,10 @@ impl Reader {
|
||||
fn placement_matrix(&mut self, item: u64, u: Units) -> R<mt::Matrix4> {
|
||||
let cx = Ctx { ex: &self.ex, len: u.len, ang: u.ang, tol: u.tol };
|
||||
let e = geom::entity(&cx, item)?;
|
||||
if matches!(e.name(), "CARTESIAN_TRANSFORMATION_OPERATOR_3D" | "CARTESIAN_TRANSFORMATION_OPERATOR_3D_NON_UNIFORM") {
|
||||
if e.name() == "CARTESIAN_TRANSFORMATION_OPERATOR_3D" {
|
||||
let p = e.params();
|
||||
let o = geom::point(&cx, p.get(4).and_then(Param::as_ref_id).ok_or("transformation without origin")?)?;
|
||||
let direction = |i: usize, fallback: mt::Vector3| -> R<mt::Vector3> {
|
||||
match p.get(i) {
|
||||
None | Some(Param::Null) => Ok(fallback),
|
||||
Some(Param::Ref(id)) => geom::direction(&cx, *id),
|
||||
_ => Err("invalid transformation direction".into()),
|
||||
}
|
||||
};
|
||||
let scale = |i: usize, fallback: f64| -> R<f64> {
|
||||
match p.get(i) {
|
||||
None | Some(Param::Null) => Ok(fallback),
|
||||
Some(v) => v.as_f64().filter(|x| x.is_finite() && *x != 0.0).ok_or_else(|| "invalid transformation scale".into()),
|
||||
}
|
||||
};
|
||||
let sx = scale(5, 1.0)?;
|
||||
let (sy, sz) = (scale(7, sx)?, scale(8, sx)?);
|
||||
let m = mt::Matrix4::from_cols(
|
||||
(direction(2, mt::Vector3::unit_x())? * sx).extend(0.0),
|
||||
(direction(3, mt::Vector3::unit_y())? * sy).extend(0.0),
|
||||
(direction(6, mt::Vector3::unit_z())? * sz).extend(0.0),
|
||||
o.to_homogeneous(),
|
||||
);
|
||||
if !to_array(&m).iter().flatten().all(|x| x.is_finite()) {
|
||||
return Err("invalid transformation scale".into());
|
||||
}
|
||||
use mt::SquareMatrix as _;
|
||||
let det = m.determinant();
|
||||
if !det.is_finite() || det == 0.0 {
|
||||
return Err("singular transformation".into());
|
||||
}
|
||||
return Ok(m);
|
||||
return Ok(mt::Matrix4::from_translation(o.to_homogeneous().truncate()));
|
||||
}
|
||||
Ok(geom::frame(&cx, item)?.matrix())
|
||||
}
|
||||
|
||||
@@ -111,30 +111,6 @@ fn seam_only_sphere_void_is_turned_inside_out() {
|
||||
assert!(rel(m.area, area) < 1e-3, "area {} vs {area}", m.area);
|
||||
}
|
||||
|
||||
/// A block with a closed cavity, written as BREP_WITH_VOIDS. SolidCraft writes the void's
|
||||
/// shell facing into the cavity with ORIENTED_CLOSED_SHELL `.T.`; some exporters write the
|
||||
/// same faces with `.F.` (#3730), which turned the void inside out and added its volume. Either
|
||||
/// way the cavity is taken out.
|
||||
#[test]
|
||||
fn a_void_reads_as_a_cavity_whichever_way_its_shell_flag_points() {
|
||||
let block = box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 12.5)).unwrap();
|
||||
let cavity = box_solid(Vec3::new(10.0, 12.0, 4.0), Vec3::new(30.0, 18.0, 9.0)).unwrap();
|
||||
let Ok(Some(hollow)) = boolean(&block, &cavity, BoolOp::Cut) else { panic!("cut") };
|
||||
let want = 40.0 * 30.0 * 12.5 - 20.0 * 6.0 * 5.0;
|
||||
assert!(rel(measure(&hollow).unwrap().volume, want) < 1e-9);
|
||||
let text = step_export(&[&hollow], "void").unwrap();
|
||||
let flag = |t: &str| t.lines().filter(|l| l.contains("ORIENTED_CLOSED_SHELL")).map(str::to_owned).collect::<Vec<_>>();
|
||||
let written = flag(&text);
|
||||
assert!(written.len() == 1 && written[0].ends_with(".T.);"), "{written:?}");
|
||||
let flipped = text.replace(&written[0], &written[0].replace(".T.);", ".F.);"));
|
||||
for t in [text, flipped] {
|
||||
let imp = step_import(&t).unwrap();
|
||||
assert!(imp.warnings.is_empty(), "{:?}", imp.warnings);
|
||||
let m = measure(&imp.bodies[0].body).unwrap();
|
||||
assert!(rel(m.volume, want) < 1e-6, "{:?}: volume {} vs {want}", flag(&t), m.volume);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_antipodal_seam_sphere_does_not_panic() {
|
||||
let text = seam_sphere_step(Vec3::ZERO, 2.0, Vec3::Z, Vec3::X, 0.0, false, 2.5);
|
||||
@@ -1770,53 +1746,3 @@ fn extruded_ellipse_patch_crossing_profile_seam_stays_trimmed() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parts of known shape from the step-conformance corpus (`tests/step-conformance`, generated
|
||||
/// from formulas by https://github.com/dan335/step-conformance at 96f30bb, CC0 1.0):
|
||||
/// each reads back with its exact volume (from the generator's own profile), its box and its
|
||||
/// face count. Left out: `torus_ring` (meshes below its equator, a meshing issue for the
|
||||
/// tessellation work) and the 1.4 MB `plate_900_holes`.
|
||||
#[test]
|
||||
fn step_conformance_parts_read_back_their_exact_shape() {
|
||||
// (file, exact volume (mm³), box (min, max), kernel faces, bodies)
|
||||
#[rustfmt::skip]
|
||||
let parts: [(&str, &str, f64, [f64; 6], usize, usize); 17] = [
|
||||
("cone_point", include_str!("../../../../tests/step-conformance/cone_point.step"), 1000.0 * std::f64::consts::PI, [-10.0, -10.0, 0.0, 10.0, 10.0, 30.0], 2, 1),
|
||||
("cone_point_vertex", include_str!("../../../../tests/step-conformance/cone_point_vertex.step"), 1000.0 * std::f64::consts::PI, [-10.0, -10.0, 0.0, 10.0, 10.0, 30.0], 2, 1),
|
||||
("cylinder", include_str!("../../../../tests/step-conformance/cylinder.step"), 9424.778, [-10.0, -10.0, 0.0, 10.0, 10.0, 30.0], 3, 1),
|
||||
("cylinder_inch", include_str!("../../../../tests/step-conformance/cylinder_inch.step"), 9424.778, [-10.0, -10.0, 0.0, 10.0, 10.0, 30.0], 3, 1),
|
||||
("cylinder_nurbs", include_str!("../../../../tests/step-conformance/cylinder_nurbs.step"), 9424.778, [-10.0, -10.0, 0.0, 10.0, 10.0, 30.0], 3, 1),
|
||||
("cylinder_placed", include_str!("../../../../tests/step-conformance/cylinder_placed.step"), 9424.778, [31.835, -33.165, 1.835, 65.485, 0.485, 35.485], 3, 1),
|
||||
("cylinder_seam", include_str!("../../../../tests/step-conformance/cylinder_seam.step"), 9424.778, [-10.0, -10.0, 0.0, 10.0, 10.0, 30.0], 3, 1),
|
||||
("cylinder_twice", include_str!("../../../../tests/step-conformance/cylinder_twice.step"), 18849.556, [-10.0, -10.0, 0.0, 90.0, 10.0, 30.0], 6, 2),
|
||||
("dome", include_str!("../../../../tests/step-conformance/dome.step"), 16755.161, [-20.0, -20.0, 0.0, 20.0, 20.0, 20.0], 2, 1),
|
||||
("dome_nurbs", include_str!("../../../../tests/step-conformance/dome_nurbs.step"), 16755.161, [-20.0, -20.0, 0.0, 20.0, 20.0, 20.0], 2, 1),
|
||||
("far_cylinder", include_str!("../../../../tests/step-conformance/far_cylinder.step"), 9424.778, [99990.0, -10.0, 0.0, 100010.0, 10.0, 30.0], 3, 1),
|
||||
("grooved_shaft", include_str!("../../../../tests/step-conformance/grooved_shaft.step"), 153532.251, [-10.0, -10.0, 0.0, 10.0, 10.0, 501.0], 753, 1),
|
||||
("plate_100_holes", include_str!("../../../../tests/step-conformance/plate_100_holes.step"), 71588.321, [0.0, 0.0, 0.0, 100.0, 100.0, 10.0], 110, 1),
|
||||
("sheet_disc", include_str!("../../../../tests/step-conformance/sheet_disc.step"), 193396443.755, [-1800.0, -1800.0, 0.0, 1800.0, 1800.0, 19.0], 3, 1),
|
||||
("tiny_pin", include_str!("../../../../tests/step-conformance/tiny_pin.step"), std::f64::consts::FRAC_PI_8, [-0.25, -0.25, 0.0, 0.25, 0.25, 2.0], 3, 1),
|
||||
("torus_ring_nurbs", include_str!("../../../../tests/step-conformance/torus_ring_nurbs.step"), 4934.802, [-25.0, -25.0, 0.0, 25.0, 25.0, 5.0], 2, 1),
|
||||
("washer", include_str!("../../../../tests/step-conformance/washer.step"), 3534.292, [-20.0, -20.0, 0.0, 20.0, 20.0, 3.0], 4, 1),
|
||||
];
|
||||
for (name, text, volume, bbox, faces, bodies) in parts {
|
||||
let imp = step_import(text).unwrap_or_else(|e| panic!("{name}: {e}"));
|
||||
assert!(imp.warnings.is_empty(), "{name}: {:?}", imp.warnings);
|
||||
assert_eq!(imp.bodies.len(), bodies, "{name}");
|
||||
let (mut v, mut n) = (0.0, 0);
|
||||
let mut b = solidcraft_geom::Aabb3::EMPTY;
|
||||
for body in &imp.bodies {
|
||||
let m = measure(&body.body).unwrap_or_else(|e| panic!("{name}: {e}"));
|
||||
v += m.volume;
|
||||
n += m.faces;
|
||||
b = b.union(&m.bbox);
|
||||
}
|
||||
assert!(rel(v, volume) < 1e-3, "{name}: volume {v} vs {volume}");
|
||||
assert_eq!(n, faces, "{name}: faces");
|
||||
let [x0, y0, z0, x1, y1, z1] = bbox;
|
||||
let size = Vec3::new(x1 - x0, y1 - y0, z1 - z0).len();
|
||||
for (got, want) in [(b.min, Vec3::new(x0, y0, z0)), (b.max, Vec3::new(x1, y1, z1))] {
|
||||
assert!(got.dist(want) <= size * 1e-3, "{name}: box corner {got:?} vs {want:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2964,53 +2964,6 @@ fn loft_pairs_the_vertices_of_matching_non_convex_sections() {
|
||||
assert!(m.centroid.x.abs() < 0.05, "centre of mass x {}", m.centroid.x);
|
||||
}
|
||||
|
||||
/// #2570: a circle lofted to a C-shaped outline. Seen from its centroid the C's vertices turn
|
||||
/// back on themselves; the circle was still split at those directions, forced to increase by
|
||||
/// whole turns, so it wound round several times (a closing arc of negative sweep), the walls
|
||||
/// crossed and the mesh grew huge. The circle is now split once round, in both section orders
|
||||
/// and from a plane facing the other way.
|
||||
#[test]
|
||||
fn loft_circle_to_non_star_profile_splits_circle_once() {
|
||||
let c = Loop2::polygon(&[
|
||||
Vec2::new(0.0, 0.0),
|
||||
Vec2::new(30.0, 0.0),
|
||||
Vec2::new(30.0, 8.0),
|
||||
Vec2::new(8.0, 8.0),
|
||||
Vec2::new(8.0, 22.0),
|
||||
Vec2::new(30.0, 22.0),
|
||||
Vec2::new(30.0, 30.0),
|
||||
Vec2::new(0.0, 30.0),
|
||||
]);
|
||||
let circle = (Plane::XY, Loop2::circle(Vec2::ZERO, 20.0));
|
||||
let up = (Plane::XY.offset(48.0), c.clone());
|
||||
let down = (Plane::new(Vec3::new(0.0, 0.0, 48.0), Vec3::Y, Vec3::X).unwrap(), c);
|
||||
for secs in [vec![circle.clone(), up.clone()], vec![up, circle.clone()], vec![circle, down]] {
|
||||
let numbered: Vec<(Plane, crate::numbered::NumberedLoop)> =
|
||||
secs.iter().map(|(p, _)| *p).zip(crate::numbered::number_loops(secs.iter().map(|(_, l)| l))).collect();
|
||||
for reversed in [false, true] {
|
||||
let loops = crate::build::loft_section_loops(&numbered, reversed).unwrap();
|
||||
let arcs: Vec<f64> = loops
|
||||
.iter()
|
||||
.flat_map(|(_, r)| r.lp.segs.iter())
|
||||
.filter_map(|s| match s {
|
||||
Seg2::Arc { sweep, .. } => Some(*sweep),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(arcs.len(), 8, "{arcs:?}");
|
||||
assert!(arcs.iter().all(|w| w.is_finite() && w.abs() > 1e-9), "{arcs:?}");
|
||||
// One way round: every arc the same way, one turn in all.
|
||||
assert!(arcs.iter().all(|w| w.signum() == arcs[0].signum()), "{arcs:?}");
|
||||
let total: f64 = arcs.iter().sum();
|
||||
assert!((total.abs() - std::f64::consts::TAU).abs() < 1e-9, "{total} {arcs:?}");
|
||||
}
|
||||
let body = loft(&secs).unwrap();
|
||||
assert!(measure(&body).unwrap().volume > 0.0);
|
||||
let mesh = body.tessellate(0.05).unwrap();
|
||||
assert!(mesh.triangles.len() < 4000, "{} triangles", mesh.triangles.len());
|
||||
}
|
||||
}
|
||||
|
||||
/// Two cylinders crossing at right angles need the kernel's own intersection: with no tries
|
||||
/// left the boolean fails at once, a budget inside another uses the outer one's up, and none
|
||||
/// lingers after.
|
||||
@@ -3028,37 +2981,6 @@ fn an_attempt_budget_stops_the_boolean_and_is_shared_by_nesting() {
|
||||
assert!(boolean(&a, &b, BoolOp::Intersect).unwrap().is_some());
|
||||
}
|
||||
|
||||
/// #2847: identical elliptic spline sections (3 x 5 mm, 30 mm off the Z axis) on planes turning
|
||||
/// about Z in 10 degree steps. The start vertex was matched by projecting the lead section's
|
||||
/// vertex directions onto each plane, which squeezes them as the plane turns (and flips them past
|
||||
/// 90 degrees), so the sections were paired round the wrong way and the loft folded (6 % of
|
||||
/// Pappus' volume at 180 degrees). The volume follows Pappus: area x 30 mm x angle.
|
||||
#[test]
|
||||
fn loft_through_identical_sections_turning_about_an_axis_keeps_its_volume() {
|
||||
let pts: Vec<Vec2> = (0..12).map(|a| Vec2::new(30.0 + 3.0 * (a as f64 * PI / 6.0).cos(), 5.0 * (a as f64 * PI / 6.0).sin())).collect();
|
||||
// Periodic Catmull-Rom through the points, as cubic Beziers.
|
||||
let segs: Vec<Seg2> = (0..12)
|
||||
.map(|i| {
|
||||
let p = |k: usize| pts[(i + k + 11) % 12];
|
||||
let (p0, p1, p2, p3) = (p(0), p(1), p(2), p(3));
|
||||
Seg2::Cubic { p0: p1, p1: p1 + (p2 - p0) * (1.0 / 6.0), p2: p2 - (p3 - p1) * (1.0 / 6.0), p3: p2 }
|
||||
})
|
||||
.collect();
|
||||
let section = Loop2 { segs };
|
||||
let area = section.signed_area().abs();
|
||||
for span in [90, 120, 180] {
|
||||
let secs: Vec<(Plane, Loop2)> = (0..=span / 10)
|
||||
.map(|i| {
|
||||
let t = (i as f64 * 10.0).to_radians();
|
||||
(Plane { origin: Vec3::ZERO, x: Vec3::new(t.cos(), t.sin(), 0.0), y: Vec3::Z }, section.clone())
|
||||
})
|
||||
.collect();
|
||||
let want = area * 30.0 * (span as f64).to_radians();
|
||||
let m = measure(&loft(&secs).unwrap()).unwrap();
|
||||
assert!(rel(m.volume, want) < 0.03, "{span} degrees: volume {} vs Pappus {want}", m.volume);
|
||||
}
|
||||
}
|
||||
|
||||
/// Moving an assembly places every body of it again: a copy placed for showing keeps its
|
||||
/// revolved faces where its source turned them, so placing searches none of them again (that search was most
|
||||
/// of the time an occurrence move took on a large assembly, #3044), and the copy is the same
|
||||
@@ -3090,45 +3012,3 @@ fn placing_a_body_does_not_turn_its_revolved_faces_again() {
|
||||
assert_eq!(a.faces, b.faces);
|
||||
assert!(a.bbox.min.dist(b.bbox.min) < 1e-9 && a.bbox.max.dist(b.bbox.max) < 1e-9);
|
||||
}
|
||||
|
||||
/// A plate 3 m long and 2 mm thick with ten holes of radius `r` along a diagonal, turned by
|
||||
/// `tilt` about the X axis and read back from STEP (each rim is then two half circles).
|
||||
fn long_plate_with_small_holes(r: f64, tilt: f64) -> (Body, Vec<Vec3>) {
|
||||
let mut p = box_solid(Vec3::new(-1500.0, -150.0, 0.0), Vec3::new(1500.0, 150.0, 2.0)).unwrap();
|
||||
let centres: Vec<Vec3> = (0..10).map(|i| Vec3::new(-1259.3 + 271.3 * i as f64, -120.0 + 27.7 * i as f64, 0.0)).collect();
|
||||
for &c in ¢res {
|
||||
let tool = cylinder(c - Vec3::Z, Vec3::Z, r, 4.0).unwrap();
|
||||
p = boolean(&p, &tool, BoolOp::Cut).unwrap().unwrap();
|
||||
}
|
||||
let shift = Vec3::new(0.0, 300.0, 300.0);
|
||||
let p = transform(&p, shift, Vec3::ZERO, Vec3::X, tilt).unwrap();
|
||||
let text = step_export(&[&p], "plate").unwrap();
|
||||
let p = step_import(&text).unwrap().bodies.remove(0).body;
|
||||
let (s, c) = tilt.sin_cos();
|
||||
let placed = centres.iter().map(|q| Vec3::new(q.x, q.y * c - q.z * s, q.y * s + q.z * c) + shift).collect();
|
||||
(p, placed)
|
||||
}
|
||||
|
||||
/// A small hole in a face of a large body, divided by a boolean. The boolean's tolerance follows
|
||||
/// the larger body (a few millimetres on a part a few metres long), so each half circle of the
|
||||
/// hole's rim was a single chord; the rim's polygon in the face's parameters had no area, and its
|
||||
/// sign, which tells a hole from a face piece, came out at random. The hole then became a face of
|
||||
/// its own, inside out, and the face it was cut in was left whole: a box cut round such a hole
|
||||
/// gave a piece without it, and the shared part of that piece and a pin in the hole came out
|
||||
/// negative or not at all.
|
||||
#[test]
|
||||
fn a_box_cut_round_a_small_hole_of_a_long_plate_keeps_the_hole() {
|
||||
for (r, tilt) in [(1.8, 0.27), (1.8, 0.7)] {
|
||||
let (p, centres) = long_plate_with_small_holes(r, tilt);
|
||||
for q in centres {
|
||||
let g = Vec3::new(8.0, 8.0, 8.0);
|
||||
let cut = box_solid(q - g, q + g).unwrap();
|
||||
let piece = boolean(&p, &cut, BoolOp::Intersect).unwrap().unwrap();
|
||||
let walls = (0..piece.face_count()).filter(|&i| matches!(face_surface(&piece, i), Some(FaceSurface::Cylinder { .. }))).count();
|
||||
// Both faces of the plate in the box keep the hole: an outer loop and the rim.
|
||||
let holed = piece.solid.face_iter().filter(|f| f.boundaries().len() == 2).count();
|
||||
assert!(walls >= 1 && holed == 2, "r {r}, tilt {tilt}, hole at {q:?}: {walls} walls, {holed} faces with a hole");
|
||||
assert!(measure(&piece).unwrap().volume > 0.0, "r {r}, tilt {tilt}, hole at {q:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,364 +0,0 @@
|
||||
//! Extrudes from a whole planar face of a body (#2040). The profile of a face is its outline
|
||||
//! projected into a sketch, and an edge that is no line or arc comes in fitted: the elliptic
|
||||
//! arcs where a fillet meets a slanted face are cubic splines a hair off the body's edges. A
|
||||
//! join's tool then touches the body along a face it does not match, and a cut's walls lie a
|
||||
//! hair inside or outside the body all round: the boolean finds pieces of no area and gives up.
|
||||
//!
|
||||
//! When the profile is the face's outline (to within the fit), the face itself is used: a join
|
||||
//! sweeps the body's own face, which shares its edges with the body and is sewn on along it, and
|
||||
//! a cut whose walls take nothing from the body (all of it within the cut's depth lies over the
|
||||
//! face) is the body cut by a slab beyond the depth plane, which meets it only across that plane.
|
||||
|
||||
use solidcraft_geom::{Mesh, Plane, Region2, Vec2, Vec3};
|
||||
use truck_modeling as mt;
|
||||
|
||||
use crate::body::{Body, v3};
|
||||
use crate::history::{Change, History};
|
||||
use crate::{KernelError, Result};
|
||||
|
||||
/// Most boundary samples compared per outline.
|
||||
const MAX_SAMPLES: usize = 20_000;
|
||||
|
||||
/// A planar face of `target` and where it lies.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct WholeFace {
|
||||
/// The face's index in `target`.
|
||||
pub face: usize,
|
||||
/// Its outward normal.
|
||||
pub normal: Vec3,
|
||||
/// Its height along the sketch normal, from the sketch plane's origin.
|
||||
pub height: f64,
|
||||
}
|
||||
|
||||
/// How far a fitted outline may lie from the face's edges: the projection fits a smooth chain to
|
||||
/// within 1e-4 of its extent (`doc::project`), and the mesh the edges are sampled from sags.
|
||||
fn outline_tol(target: &Body) -> f64 {
|
||||
(target.size() * 5e-4).max(1e-4)
|
||||
}
|
||||
|
||||
/// The planar face of `target` at one of `heights` along `plane`'s normal (from its origin)
|
||||
/// whose outline is `region`'s outer loop, to within the projection's fit, with no holes on
|
||||
/// either side.
|
||||
pub fn matching_face(target: &Body, plane: &Plane, region: &Region2, heights: &[f64]) -> Option<WholeFace> {
|
||||
if !region.holes.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let n = plane.normal();
|
||||
let tol = outline_tol(target);
|
||||
let mesh = target.tessellate(tol * 0.2).ok()?;
|
||||
let ring: Vec<Vec2> = region.outer.polyline(tol * 0.1).into_vec();
|
||||
if ring.len() < 3 || ring.len() > MAX_SAMPLES {
|
||||
return None;
|
||||
}
|
||||
let faces: Vec<&mt::Face> = target.solid.face_iter().collect();
|
||||
for (i, f) in faces.iter().enumerate() {
|
||||
let Some(m) = crate::blend::plane_normal(f) else { continue };
|
||||
if m.dot(n).abs() < 1.0 - 1e-9 || f.boundaries().len() != 1 {
|
||||
continue;
|
||||
}
|
||||
let edges = face_outline(&mesh, i);
|
||||
let Some(height) = edges.first().and_then(|e| e.first()).map(|p| (*p - plane.origin).dot(n)) else { continue };
|
||||
if !heights.iter().any(|h| (h - height).abs() <= tol) {
|
||||
continue;
|
||||
}
|
||||
// The outline in the sketch's plane, at the face's height.
|
||||
let at = |p: Vec2| plane.to_world(p) + n * height;
|
||||
let ring3: Vec<Vec3> = ring.iter().map(|p| at(*p)).collect();
|
||||
let segs: Vec<(Vec3, Vec3)> = edges.iter().flat_map(|e| e.windows(2).filter_map(|w| Some((*w.first()?, *w.get(1)?)))).collect();
|
||||
if segs.is_empty() || segs.len() > MAX_SAMPLES {
|
||||
continue;
|
||||
}
|
||||
let near_edges = |p: Vec3| segs.iter().any(|(a, b)| p.dist_to_segment(*a, *b) <= tol);
|
||||
let ring_segs: Vec<(Vec3, Vec3)> = (0..ring3.len()).filter_map(|k| Some((*ring3.get(k)?, *ring3.get((k + 1) % ring3.len())?))).collect();
|
||||
let near_ring = |p: Vec3| ring_segs.iter().any(|(a, b)| p.dist_to_segment(*a, *b) <= tol);
|
||||
let off_plane = segs.iter().any(|(a, _)| ((*a - plane.origin).dot(n) - height).abs() > tol);
|
||||
if !off_plane && ring3.iter().all(|p| near_edges(*p)) && segs.iter().all(|(a, _)| near_ring(*a)) {
|
||||
return Some(WholeFace { face: i, normal: m, height });
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The boundary polylines of face `face` of `mesh`, seams left out.
|
||||
fn face_outline(mesh: &Mesh, face: usize) -> Vec<Vec<Vec3>> {
|
||||
let Ok(f) = u32::try_from(face) else { return Vec::new() };
|
||||
mesh.face_edges(f).into_iter().filter(|e| !mesh.seams.get(*e).copied().unwrap_or(false)).filter_map(|e| mesh.edges.get(e).cloned()).collect()
|
||||
}
|
||||
|
||||
/// The prism `built` (made from a profile that [`matching_face`] matched to `face`) made again
|
||||
/// from the face itself: the face swept `length` along its outward normal, `outward` or back
|
||||
/// into the body. Each of its faces comes from the face of `built` it lies on, so the feature
|
||||
/// names its faces as it named `built`'s.
|
||||
pub fn face_prism(target: &Body, face: WholeFace, length: f64, outward: bool, built: &Body) -> Result<Body> {
|
||||
if !length.is_finite() || length <= 0.0 {
|
||||
return Err(KernelError::Invalid("a prism from a face needs a positive length".into()));
|
||||
}
|
||||
let f = target.solid.face_iter().nth(face.face).cloned().ok_or_else(|| KernelError::Invalid("no such face".into()))?;
|
||||
let along = if outward { face.normal * length } else { face.normal * -length };
|
||||
let swept = crate::guard("prism from a face", || Body::new(mt::builder::tsweep(&f, v3(along))))?;
|
||||
traced_onto(swept, built, outline_tol(target))
|
||||
}
|
||||
|
||||
/// `swept`, made in place of `built`, with each of its faces coming from the face of `built`
|
||||
/// nearest it (so a feature names its faces as it named `built`'s).
|
||||
fn traced_onto(swept: Body, built: &Body, tol: f64) -> Result<Body> {
|
||||
let (mine, theirs) = (swept.tessellate(tol)?, built.tessellate(tol)?);
|
||||
let mut faces = Vec::with_capacity(swept.face_count());
|
||||
for i in 0..swept.face_count() {
|
||||
let probe = face_probe(&mine, i).ok_or_else(|| KernelError::Failed("tool from a face: a face with no mesh".into()))?;
|
||||
let from = nearest_face(&theirs, probe).ok_or_else(|| KernelError::Failed("tool from a face: no face under it".into()))?;
|
||||
faces.push(crate::record::from_face(0, from, Change::Modified));
|
||||
}
|
||||
let history: History = crate::record::from_faces(&swept.solid, 1, faces);
|
||||
swept.with_history_counts(history, &crate::record::counts(&[built]))
|
||||
}
|
||||
|
||||
/// The centroid of face `face`'s largest triangle.
|
||||
fn face_probe(mesh: &Mesh, face: usize) -> Option<Vec3> {
|
||||
let f = u32::try_from(face).ok()?;
|
||||
mesh.triangles
|
||||
.iter()
|
||||
.zip(&mesh.tri_face)
|
||||
.filter(|(_, tf)| **tf == f)
|
||||
.filter_map(|(t, _)| mesh.tri(t))
|
||||
.max_by(|x, y| (x[1] - x[0]).cross(x[2] - x[0]).len().total_cmp(&(y[1] - y[0]).cross(y[2] - y[0]).len()))
|
||||
.map(|[a, b, c]| (a + b + c) / 3.0)
|
||||
}
|
||||
|
||||
/// The face of `mesh` nearest `p`.
|
||||
fn nearest_face(mesh: &Mesh, p: Vec3) -> Option<usize> {
|
||||
mesh.triangles
|
||||
.iter()
|
||||
.zip(&mesh.tri_face)
|
||||
.filter_map(|(t, f)| mesh.tri(t).map(|[a, b, c]| (crate::polyhedron::point_tri(p, a, b, c), *f)))
|
||||
.min_by(|x, y| x.0.total_cmp(&y.0))
|
||||
.and_then(|(_, f)| usize::try_from(f).ok())
|
||||
}
|
||||
|
||||
/// Whether a cut `depth` into `target` from `face` takes only what lies over the face: nothing of
|
||||
/// the body stands beyond the face's plane, and everything of it less than `depth` below lies
|
||||
/// over the face (on its outline at most). Then the prism over the face and a slab over the whole
|
||||
/// body take the same material, and the slab meets the body only across its depth plane.
|
||||
pub fn cut_takes_only_the_face(target: &Body, face: WholeFace, depth: f64) -> bool {
|
||||
if !depth.is_finite() || depth <= 0.0 {
|
||||
return false;
|
||||
}
|
||||
let tol = outline_tol(target);
|
||||
let Ok(mesh) = target.tessellate(tol * 0.2) else { return false };
|
||||
let Some(origin) = face_outline(&mesh, face.face).first().and_then(|e| e.first().copied()) else { return false };
|
||||
let n = face.normal;
|
||||
// The face's plane with the outline in it, flattened.
|
||||
let Some(x) = (if n.x.abs() < 0.9 { Vec3::X } else { Vec3::Y }).cross(n).normalized() else { return false };
|
||||
let y = n.cross(x);
|
||||
let flat = |p: Vec3| Vec2::new((p - origin).dot(x), (p - origin).dot(y));
|
||||
let segs: Vec<(Vec2, Vec2)> = face_outline(&mesh, face.face)
|
||||
.iter()
|
||||
.flat_map(|e| e.windows(2).filter_map(|w| Some((flat(*w.first()?), flat(*w.get(1)?)))).collect::<Vec<_>>())
|
||||
.collect();
|
||||
if segs.len() < 3 || segs.len() > MAX_SAMPLES {
|
||||
return false;
|
||||
}
|
||||
let mut points = mesh.positions.clone();
|
||||
points.extend(mesh.triangles.iter().filter_map(|t| mesh.tri(t)).map(|[a, b, c]| (a + b + c) / 3.0));
|
||||
points.iter().all(|p| {
|
||||
let h = (*p - origin).dot(n);
|
||||
h <= tol && (h <= -depth + tol || over(&segs, flat(*p), tol))
|
||||
})
|
||||
}
|
||||
|
||||
/// How a wall swept into the body from an edge of the face meets the body along that edge, from
|
||||
/// the face beside it (outward normal `n_N`) and the sweep's direction `−n_P`: `n_N · (−n_P)`
|
||||
/// above zero leaves the body (the wall only touches it along the edge), zero lies in the face
|
||||
/// beside it, below zero goes into the material (a real cut).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Wall {
|
||||
Touches,
|
||||
Cuts,
|
||||
}
|
||||
|
||||
/// The walls of each edge of face `face` of `mesh` (by mesh edge), `None` where an edge's wall
|
||||
/// changes from one to the other along it.
|
||||
fn walls(mesh: &Mesh, face: usize, n: Vec3, tol: f64) -> Option<Vec<(usize, Wall)>> {
|
||||
let f = u32::try_from(face).ok()?;
|
||||
let mut out = Vec::new();
|
||||
for e in mesh.face_edges(f) {
|
||||
if mesh.seams.get(e).copied().unwrap_or(false) {
|
||||
continue;
|
||||
}
|
||||
let other = mesh.edge_faces.get(e)?.iter().copied().find(|g| *g != f)?;
|
||||
let pts = mesh.edges.get(e)?;
|
||||
let tris: Vec<[Vec3; 3]> = mesh.triangles.iter().zip(&mesh.tri_face).filter(|(_, g)| **g == other).filter_map(|(t, _)| mesh.tri(t)).collect();
|
||||
let dist = |p: Vec3, t: &[Vec3; 3]| crate::polyhedron::point_tri(p, t[0], t[1], t[2]);
|
||||
// Each point's nearest triangle of the face beside, by its normal.
|
||||
let mut signs = pts.iter().filter_map(|p| {
|
||||
let [a, b, c] = *tris.iter().min_by(|x, y| dist(*p, x).total_cmp(&dist(*p, y)))?;
|
||||
let m = (b - a).cross(c - a).normalized()?;
|
||||
Some(if -m.dot(n) >= -tol { Wall::Touches } else { Wall::Cuts })
|
||||
});
|
||||
let first = signs.next()?;
|
||||
if signs.any(|s| s != first) {
|
||||
return None;
|
||||
}
|
||||
out.push((e, first));
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Whether `q` lies inside the outline made of `segs` (in any order and direction, by even-odd
|
||||
/// crossings) or within `tol` of it.
|
||||
fn over(segs: &[(Vec2, Vec2)], q: Vec2, tol: f64) -> bool {
|
||||
let on = segs.iter().any(|(a, b)| {
|
||||
let ab = *b - *a;
|
||||
let t = if ab.len2() > 0.0 { ((q - *a).dot(ab) / ab.len2()).clamp(0.0, 1.0) } else { 0.0 };
|
||||
q.dist(*a + ab * t) <= tol
|
||||
});
|
||||
on || segs.iter().filter(|(a, b)| (a.y > q.y) != (b.y > q.y) && q.x < a.x + (q.y - a.y) / (b.y - a.y) * (b.x - a.x)).count() % 2 == 1
|
||||
}
|
||||
|
||||
/// Even-odd containment of `q` in the closed polygon `poly`.
|
||||
fn inside(poly: &[Vec2], q: Vec2) -> bool {
|
||||
let m = poly.len();
|
||||
(0..m)
|
||||
.filter(|i| match (poly.get(*i), poly.get((i + 1) % m)) {
|
||||
(Some(a), Some(b)) => (a.y > q.y) != (b.y > q.y) && q.x < a.x + (q.y - a.y) / (b.y - a.y) * (b.x - a.x),
|
||||
_ => false,
|
||||
})
|
||||
.count()
|
||||
% 2
|
||||
== 1
|
||||
}
|
||||
|
||||
/// A tool cutting `depth` into `target` from its planar face `face`, as the face swept would, with
|
||||
/// the walls that only touch the body moved off it: the face's outline keeps its edges whose walls
|
||||
/// cut into the body, exactly (the body's own edges), and runs round the others well outside it.
|
||||
/// The tool starts a little out from the face, so its cap does not lie on it. `None` when no wall
|
||||
/// cuts (the face's prism takes only what is over it, see [`cut_takes_only_the_face`]), when an
|
||||
/// edge's wall changes from touching to cutting along it, or when anything of the body within the
|
||||
/// depth lies where the outline runs round. Its faces come from those of `built` (the profile's
|
||||
/// own tool) they lie nearest, when given. With how far out from the face it starts.
|
||||
pub fn cut_tool(target: &Body, face: WholeFace, depth: f64, built: Option<&Body>) -> Option<(Body, f64)> {
|
||||
// Every step reads or builds truck's shapes, so all of it runs under the guard.
|
||||
crate::guard("cut tool from a face", || Ok(build_cut_tool(target, face, depth, built))).ok().flatten()
|
||||
}
|
||||
|
||||
fn build_cut_tool(target: &Body, face: WholeFace, depth: f64, built: Option<&Body>) -> Option<(Body, f64)> {
|
||||
use mt::{BoundedCurve, ParametricCurve};
|
||||
use std::f64::consts::{PI, TAU};
|
||||
if !depth.is_finite() || depth <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let size = target.size();
|
||||
let tol = outline_tol(target);
|
||||
let mesh = target.tessellate(tol * 0.2).ok()?;
|
||||
let n = face.normal;
|
||||
let walls = walls(&mesh, face.face, n, 1e-6)?;
|
||||
if !walls.iter().any(|(_, w)| *w == Wall::Cuts) || !walls.iter().any(|(_, w)| *w == Wall::Touches) {
|
||||
return None;
|
||||
}
|
||||
let f = target.solid.face_iter().nth(face.face)?.clone();
|
||||
let wire = f.absolute_boundaries().first()?.clone();
|
||||
// Each edge of the face's outline (in order) with its wall, matched to the mesh's edges by
|
||||
// their middles.
|
||||
let mid = |e: &mt::Edge| {
|
||||
let c = e.curve();
|
||||
let (t0, t1) = c.range_tuple();
|
||||
crate::body::from_p3(c.subs((t0 + t1) * 0.5))
|
||||
};
|
||||
let wall_of = |e: &mt::Edge| {
|
||||
let m = mid(e);
|
||||
walls
|
||||
.iter()
|
||||
.filter_map(|(i, w)| {
|
||||
let pts = mesh.edges.get(*i)?;
|
||||
Some((pts.windows(2).filter_map(|s| Some(m.dist_to_segment(*s.first()?, *s.get(1)?))).fold(f64::INFINITY, f64::min), *w))
|
||||
})
|
||||
.min_by(|a, b| a.0.total_cmp(&b.0))
|
||||
.filter(|(d, _)| *d <= tol)
|
||||
.map(|(_, w)| w)
|
||||
};
|
||||
let edges: Vec<(mt::Edge, Wall)> = wire.edge_iter().map(|e| wall_of(e).map(|w| (e.clone(), w))).collect::<Option<_>>()?;
|
||||
// Start at a cutting edge that follows a touching one.
|
||||
let k = edges.len();
|
||||
let start =
|
||||
(0..k).find(|i| edges.get(*i).is_some_and(|e| e.1 == Wall::Cuts) && edges.get((i + k - 1) % k).is_some_and(|e| e.1 == Wall::Touches))?;
|
||||
let edges: Vec<(mt::Edge, Wall)> = edges.iter().cycle().skip(start).take(k).cloned().collect();
|
||||
// The plane's frame, round the face's middle.
|
||||
let origin = face_probe(&mesh, face.face)?;
|
||||
let x = (if n.x.abs() < 0.9 { Vec3::X } else { Vec3::Y }).cross(n).normalized()?;
|
||||
let y = n.cross(x);
|
||||
let flat = |p: Vec3| Vec2::new((p - origin).dot(x), (p - origin).dot(y));
|
||||
let lift = |q: Vec2| origin + x * q.x + y * q.y;
|
||||
let outline: Vec<(Vec2, Vec2)> = face_outline(&mesh, face.face)
|
||||
.iter()
|
||||
.flat_map(|e| e.windows(2).filter_map(|w| Some((flat(*w.first()?), flat(*w.get(1)?)))).collect::<Vec<_>>())
|
||||
.collect();
|
||||
let centre = outline.iter().fold(Vec2::ZERO, |a, (p, _)| a + *p) / outline.len().max(1) as f64;
|
||||
let far = size * 2.0;
|
||||
let at = |v: &mt::Vertex| flat(crate::body::from_p3(v.point()));
|
||||
// Which way the outline runs round its middle.
|
||||
let turn: f64 = edges.iter().map(|(e, _)| (at(e.front()) - centre).cross(at(e.back()) - centre)).sum::<f64>().signum();
|
||||
let mut out: Vec<mt::Edge> = Vec::new();
|
||||
let mut detours: Vec<Vec<Vec2>> = Vec::new();
|
||||
let mut i = 0;
|
||||
while let Some((e, w)) = edges.get(i) {
|
||||
if *w == Wall::Cuts {
|
||||
out.push(e.clone());
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
// A run of touching edges from vertex `a` to vertex `b`: round it, far out.
|
||||
let a = e.front().clone();
|
||||
let mut j = i;
|
||||
while edges.get(j).is_some_and(|e| e.1 == Wall::Touches) {
|
||||
j += 1;
|
||||
}
|
||||
let b = edges.get(j - 1)?.0.back().clone();
|
||||
let (pa, pb) = (at(&a), at(&b));
|
||||
let (da, db) = ((pa - centre).normalized()?, (pb - centre).normalized()?);
|
||||
let (t0, mut t1) = (da.y.atan2(da.x), db.y.atan2(db.x));
|
||||
// Round the same way as the run, which goes from a to b with the outline.
|
||||
while (t1 - t0) * turn <= 0.0 {
|
||||
t1 += TAU * turn;
|
||||
}
|
||||
let steps = (((t1 - t0).abs() / (PI / 8.0)).ceil() as usize).clamp(2, 64);
|
||||
// A polygon round a circle `far` out (its corners 1/cos(π/16) further), clear of it.
|
||||
let r = far / (PI / 16.0).cos();
|
||||
let mut path = vec![pa];
|
||||
path.extend((0..=steps).map(|s| {
|
||||
let t = t0 + (t1 - t0) * s as f64 / steps as f64;
|
||||
centre + Vec2::new(t.cos(), t.sin()) * if s == 0 || s == steps { far } else { r }
|
||||
}));
|
||||
path.push(pb);
|
||||
let mut verts = vec![a];
|
||||
verts.extend(path.iter().skip(1).take(path.len().saturating_sub(2)).map(|q| mt::builder::vertex(crate::body::p3(lift(*q)))));
|
||||
verts.push(b);
|
||||
out.extend(verts.windows(2).filter_map(|v| Some(mt::builder::line(v.first()?, v.get(1)?))));
|
||||
detours.push(path);
|
||||
i = j;
|
||||
}
|
||||
// Nothing of the body within the depth may lie where the outline runs round.
|
||||
let clear = mesh.positions.iter().all(|p| {
|
||||
let h = (*p - origin).dot(n);
|
||||
let q = flat(*p);
|
||||
h >= tol || h <= -depth + tol || !detours.iter().any(|d| inside(d, q)) || over(&outline, q, tol)
|
||||
});
|
||||
if !clear {
|
||||
return None;
|
||||
}
|
||||
let mut base = mt::Face::try_new(vec![mt::Wire::from(out)], f.surface()).ok()?;
|
||||
if !f.orientation() {
|
||||
base.invert();
|
||||
}
|
||||
// Out from the face, then swept back through it and the depth.
|
||||
let off = (size * 1e-2).max(tol * 10.0);
|
||||
let base = mt::builder::translated(&base, v3(n * off));
|
||||
let tool = Body::new(mt::builder::tsweep(&base, v3(n * -(off + depth)))).ok()?;
|
||||
match built {
|
||||
Some(built) => traced_onto(tool, built, tol).ok().map(|t| (t, off)),
|
||||
None => Some((tool, off)),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "whole_face_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,110 +0,0 @@
|
||||
use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2, Vec3};
|
||||
|
||||
use super::*;
|
||||
use crate::{BoolOp, boolean, box_solid, measure};
|
||||
|
||||
fn square(a: Vec2, b: Vec2) -> Region2 {
|
||||
let p = Vec2::new;
|
||||
let line = |a: Vec2, b: Vec2| Seg2::Line { a, b };
|
||||
Region2 { outer: Loop2 { segs: vec![line(a, p(b.x, a.y)), line(p(b.x, a.y), b), line(b, p(a.x, b.y)), line(p(a.x, b.y), a)] }, holes: vec![] }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_profile_matches_the_face_it_outlines_and_no_other() {
|
||||
let block = box_solid(Vec3::ZERO, Vec3::new(20.0, 10.0, 5.0)).unwrap();
|
||||
let top = Plane { origin: Vec3::new(0.0, 0.0, 5.0), ..Plane::XY };
|
||||
let whole = matching_face(&block, &top, &square(Vec2::new(0.0, 0.0), Vec2::new(20.0, 10.0)), &[0.0]).unwrap();
|
||||
assert!((whole.normal - Vec3::Z).len() < 1e-9 && whole.height.abs() < 1e-9, "{whole:?}");
|
||||
// A smaller rectangle on the same face is not the face.
|
||||
assert!(matching_face(&block, &top, &square(Vec2::new(1.0, 1.0), Vec2::new(19.0, 9.0)), &[0.0]).is_none());
|
||||
// Nor is the bottom face, though its outline is the same.
|
||||
assert!(matching_face(&block, &top, &square(Vec2::ZERO, Vec2::new(20.0, 10.0)), &[-3.0]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cut_over_the_whole_top_takes_only_the_face_and_a_step_beside_it_does_not() {
|
||||
let block = box_solid(Vec3::ZERO, Vec3::new(20.0, 10.0, 5.0)).unwrap();
|
||||
let top =
|
||||
matching_face(&block, &Plane { origin: Vec3::new(0.0, 0.0, 5.0), ..Plane::XY }, &square(Vec2::ZERO, Vec2::new(20.0, 10.0)), &[0.0]).unwrap();
|
||||
assert!(cut_takes_only_the_face(&block, top, 2.0));
|
||||
// A step standing beside the top face: a slab would take it too.
|
||||
let step = box_solid(Vec3::new(20.0, 0.0, 0.0), Vec3::new(30.0, 10.0, 8.0)).unwrap();
|
||||
let stepped = boolean(&block, &step, BoolOp::Union).unwrap().unwrap();
|
||||
let face = matching_face(&stepped, &Plane { origin: Vec3::new(0.0, 0.0, 5.0), ..Plane::XY }, &square(Vec2::ZERO, Vec2::new(20.0, 10.0)), &[0.0])
|
||||
.unwrap();
|
||||
assert!(!cut_takes_only_the_face(&stepped, face, 2.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prism_from_the_face_joins_by_its_shared_edges() {
|
||||
let block = box_solid(Vec3::ZERO, Vec3::new(20.0, 10.0, 5.0)).unwrap();
|
||||
let plane = Plane { origin: Vec3::new(0.0, 0.0, 5.0), ..Plane::XY };
|
||||
let region = square(Vec2::ZERO, Vec2::new(20.0, 10.0));
|
||||
let face = matching_face(&block, &plane, ®ion, &[0.0]).unwrap();
|
||||
let built = crate::extrude(&plane, std::slice::from_ref(®ion), 0.0, 3.0).unwrap().remove(0);
|
||||
let tool = face_prism(&block, face, 3.0, true, &built).unwrap();
|
||||
assert!(tool.history().is_some_and(|h| h.operands == 1));
|
||||
let joined = boolean(&block, &tool, BoolOp::Union).unwrap().unwrap();
|
||||
assert!((measure(&joined).unwrap().volume - 20.0 * 10.0 * 8.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
/// The block of #2040: one side at 45°, its top (and, with `bottom`, its bottom) rounded 3.8 mm
|
||||
/// at both ends.
|
||||
fn rounded_block(bottom: bool) -> Body {
|
||||
let p = Vec2::new;
|
||||
let line = |a: Vec2, b: Vec2| Seg2::Line { a, b };
|
||||
let h = 8.485281374238571;
|
||||
let segs = vec![
|
||||
line(p(0.0, 0.0), p(11.514718625761429, 0.0)),
|
||||
line(p(11.514718625761429, 0.0), p(20.0, h)),
|
||||
line(p(20.0, h), p(0.0, h)),
|
||||
line(p(0.0, h), p(0.0, 0.0)),
|
||||
];
|
||||
let plane = Plane { origin: Vec3::ZERO, x: Vec3::X, y: Vec3::Z };
|
||||
let block = crate::extrude(&plane, &[Region2 { outer: Loop2 { segs }, holes: vec![] }], 0.0, 10.0).unwrap().remove(0);
|
||||
let mut edges = vec![Vec3::new(10.0, -10.0, h), Vec3::new(10.0, 0.0, h)];
|
||||
if bottom {
|
||||
edges.extend([Vec3::new(5.757359312880714, 0.0, 0.0), Vec3::new(5.757359312880714, -10.0, 0.0)]);
|
||||
}
|
||||
crate::fillet(&block, &edges, 3.8).unwrap()
|
||||
}
|
||||
|
||||
fn slanted_face(b: &Body) -> WholeFace {
|
||||
let n = Vec3::new(1.0, 0.0, -1.0).normalized().unwrap();
|
||||
let face = b.solid.face_iter().position(|f| crate::blend::plane_normal(f).is_some_and(|m| m.dot(n) > 1.0 - 1e-9)).unwrap();
|
||||
WholeFace { face, normal: n, height: 0.0 }
|
||||
}
|
||||
|
||||
/// Into the slanted face, the walls from its top edge and the rounds beside it leave the body
|
||||
/// (n_N · −n_P = +0.707 down to 0), those from the end faces lie in them (0), and those from the
|
||||
/// bottom edge and its rounds go into it (−0.707 up to 0): the bottom ones are kept, the others
|
||||
/// moved off.
|
||||
#[test]
|
||||
fn the_walls_into_a_slanted_face_touch_at_the_top_and_cut_at_the_bottom() {
|
||||
let b = rounded_block(true);
|
||||
let face = slanted_face(&b);
|
||||
let mesh = b.tessellate(outline_tol(&b) * 0.2).unwrap();
|
||||
let walls = walls(&mesh, face.face, face.normal, 1e-6).unwrap();
|
||||
assert_eq!(walls.iter().filter(|(_, w)| *w == Wall::Cuts).count(), 3, "{walls:?}");
|
||||
assert_eq!(walls.iter().filter(|(_, w)| *w == Wall::Touches).count(), 5, "{walls:?}");
|
||||
assert!(!cut_takes_only_the_face(&b, face, 3.0));
|
||||
assert!(cut_tool(&b, face, 3.0, None).is_some());
|
||||
}
|
||||
|
||||
/// A cut 3 mm into the slanted face of the block rounded along its top: the walls from the top
|
||||
/// are moved off it, the one from the bottom edge kept. What it takes: in the face's plane, the
|
||||
/// body's section at depth t is the block's section (10 wide, h high, its top corners rounded)
|
||||
/// moved down the face by t, so the cut takes √2 ∫₀³ (10 (h − t/√2) − 2 (1 − π/4) r²) dt.
|
||||
#[test]
|
||||
fn a_cut_into_a_slanted_face_beside_rounds_takes_what_lies_over_it() {
|
||||
let b = rounded_block(false);
|
||||
let face = slanted_face(&b);
|
||||
let (tool, _) = cut_tool(&b, face, 3.0, None).unwrap();
|
||||
let cut = boolean(&b, &tool, BoolOp::Cut).unwrap().unwrap();
|
||||
assert!(cut.validity().is_empty(), "{:?}", cut.validity());
|
||||
let (h, r, d, w) = (8.485281374238571_f64, 3.8_f64, 3.0_f64, 10.0_f64);
|
||||
let corner = (1.0 - std::f64::consts::FRAC_PI_4) * r * r;
|
||||
let taken = 2f64.sqrt() * w * h * d - w * d * d / 2.0 - 2.0 * 2f64.sqrt() * corner * d;
|
||||
let v = measure(&b).unwrap().volume - measure(&cut).unwrap().volume;
|
||||
assert!((v - taken).abs() < 0.05, "took {v}, expected {taken}");
|
||||
}
|
||||
@@ -421,35 +421,6 @@ fn batch_rolls_back_with_a_full_undo_history() {
|
||||
assert_eq!(d["undo"], undo);
|
||||
}
|
||||
|
||||
/// Regression (#3242): a failed batch containing `file.new` reported `rolled_back: true` and
|
||||
/// kept the replacement design. The checkpoint survives the new document, so the design the
|
||||
/// batch started in — the 1 mm cube — is back when the batch fails.
|
||||
#[test]
|
||||
fn a_failed_batch_with_file_new_restores_the_original_design() {
|
||||
let mut s = server();
|
||||
tool(&mut s, "batch", json!({"commands": [{"command": "solid.box", "params": {"length": 1, "width": 1, "height": 1, "body_name": "Original"}}]}));
|
||||
let name = tool(&mut s, "inspect_design", json!({"measure": false, "sketches": false}))["name"].clone();
|
||||
let r = raw_tool(
|
||||
&mut s,
|
||||
"batch",
|
||||
json!({"rollback": true, "commands": [
|
||||
{"command": "file.new", "params": {"name": "Replacement"}},
|
||||
{"command": "solid.box", "params": {"length": 2, "width": 2, "height": 2}},
|
||||
{"command": "not.a.command"},
|
||||
]}),
|
||||
);
|
||||
assert_eq!(r["result"]["isError"], true, "{r}");
|
||||
let body: Value = serde_json::from_str(r["result"]["content"][0]["text"].as_str().unwrap()).unwrap();
|
||||
assert_eq!(body["failed"]["index"], 2, "{body}");
|
||||
assert_eq!(body["rolled_back"], true, "{body}");
|
||||
assert_eq!(body["undone"], 2, "{body}");
|
||||
// The original 1 mm cube is back; the replacement design is gone.
|
||||
assert_eq!(tool(&mut s, "measure", json!({}))["body_count"], 1);
|
||||
assert!(rel(volume(&mut s), 1.0) < 1e-9, "{}", volume(&mut s));
|
||||
let d = tool(&mut s, "inspect_design", json!({"measure": false, "sketches": false}));
|
||||
assert_eq!(d["name"], name, "{d}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn helper_sketches_can_be_hidden() {
|
||||
let mut s = server();
|
||||
@@ -1375,27 +1346,6 @@ fn batch_reports_a_failed_engine_batch_like_before() {
|
||||
);
|
||||
}
|
||||
|
||||
/// `rolled_back` tells whether the design went back, not whether a rollback was asked for
|
||||
/// (#3242): the app's `rolled_back`, or, for an app that predates that field, none of the
|
||||
/// completed steps undone means the design did not go back.
|
||||
#[test]
|
||||
fn a_batch_the_app_could_not_roll_back_reports_it() {
|
||||
let failed = |reply: Value| {
|
||||
let (_, body, is_error) = recorded_batch(Ok(reply), json!({"commands": [{"command": "a.one"}, {"command": "a.two"}]}));
|
||||
assert!(is_error);
|
||||
body
|
||||
};
|
||||
let body = failed(
|
||||
json!({"completed": 1, "results": [{"x": 1}], "failed": {"index": 1, "command": "a.two", "error": "boom"}, "rolled_back": false, "undone": 0}),
|
||||
);
|
||||
assert_eq!(body["rolled_back"], false, "{body}");
|
||||
let body = failed(json!({"completed": 1, "results": [{"x": 1}], "failed": {"index": 1, "command": "a.two", "error": "boom"}, "undone": 0}));
|
||||
assert_eq!(body["rolled_back"], false, "{body}");
|
||||
// A first step that failed left nothing to take back.
|
||||
let body = failed(json!({"completed": 0, "results": [], "failed": {"index": 0, "command": "a.one", "error": "boom"}, "undone": 0}));
|
||||
assert_eq!(body["rolled_back"], true, "{body}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_falls_back_when_the_app_lacks_engine_batch() {
|
||||
let (b, body, is_error) =
|
||||
|
||||
+20
-29
@@ -278,7 +278,7 @@ pub fn tool_definitions() -> Vec<Value> {
|
||||
json!({
|
||||
"path": string("Path to a .solidcraft, .step/.stp, .3mf, .stl, .obj, .glb or .gltf file"),
|
||||
"up": {"type": "string", "enum": ["z", "y"], "description": "STEP and glTF only. z keeps the file's axes; y: the file has Y up, so its bodies are turned to stand Z up. Default: z for STEP, y for glTF"},
|
||||
"names": {"type": "string", "enum": ["auto", "solid", "product", "instance"], "description": "STEP, IGES, FreeCAD and Rhino. auto (default): keep meaningful solid names, replace placeholders with the nearest named product, else instance; solid: the solid's own name; product: the part's name; instance: the occurrence's name, else the product's"},
|
||||
"names": {"type": "string", "enum": ["solid", "product", "instance"], "description": "STEP only. What the bodies are named after: solid (default: the solid's own name, else the product's), product (the part's name) or instance (the assembly occurrence's name, else the product's)"},
|
||||
}),
|
||||
&["path"],
|
||||
),
|
||||
@@ -500,13 +500,12 @@ impl Undo {
|
||||
}
|
||||
}
|
||||
|
||||
/// Go back; (whether the design is back as it was, the number of steps undone). A failed
|
||||
/// rollback says so rather than reporting the flag the caller asked for (#3242).
|
||||
fn rollback(self, b: &mut dyn Backend, steps: usize) -> (bool, u64) {
|
||||
/// Go back; the number of steps undone.
|
||||
fn rollback(self, b: &mut dyn Backend, steps: usize) -> u64 {
|
||||
match self {
|
||||
Undo::Checkpoint(id) => match exec(b, "edit.restore_checkpoint", json!({"checkpoint": id})) {
|
||||
Ok(_) => (true, steps as u64),
|
||||
Err(_) => (false, 0),
|
||||
Ok(_) => steps as u64,
|
||||
Err(_) => 0,
|
||||
},
|
||||
Undo::Depth(before) => {
|
||||
let after = undo_depth(b).unwrap_or(before);
|
||||
@@ -517,10 +516,9 @@ impl Undo {
|
||||
}
|
||||
undone += 1;
|
||||
}
|
||||
(undone == steps as u64, undone)
|
||||
undone
|
||||
}
|
||||
// Nothing remembered the design; only a first step that failed left nothing behind.
|
||||
Undo::None => (steps == 0, 0),
|
||||
Undo::None => 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -585,12 +583,12 @@ fn batch(b: &mut dyn Backend, a: &Map<String, Value>) -> Value {
|
||||
match r {
|
||||
Ok(v) => results.push(if verbose { v } else { compact(v) }),
|
||||
Err(e) => {
|
||||
let (rolled_back, undone) = start.rollback(b, i);
|
||||
let undone = start.rollback(b, i);
|
||||
let reply = json!({
|
||||
"ok": false,
|
||||
"completed": i,
|
||||
"failed": {"index": i, "command": command, "error": e},
|
||||
"rolled_back": rolled_back,
|
||||
"rolled_back": rollback,
|
||||
"undone": undone,
|
||||
"results": results,
|
||||
});
|
||||
@@ -618,24 +616,17 @@ fn batch_reply(r: &Value, rollback: bool, verbose: bool) -> Value {
|
||||
r["results"].as_array().cloned().unwrap_or_default().into_iter().map(|v| if verbose { v } else { compact(v) }).collect();
|
||||
let (mut reply, error) = match r.get("failed").filter(|f| !f.is_null()) {
|
||||
None => (json!({"ok": true, "completed": results.len(), "results": results}), false),
|
||||
Some(failed) => {
|
||||
// `rolled_back` tells whether the design went back, not whether a rollback was
|
||||
// asked for (#3242): the app answers with its own `rolled_back`; an app that
|
||||
// predates that field and undid none of the steps it had completed did not go back.
|
||||
let undone = r["undone"].as_u64().unwrap_or(0);
|
||||
let went_back = r.get("rolled_back").and_then(Value::as_bool).unwrap_or(undone > 0 || r["completed"].as_u64() == Some(0));
|
||||
(
|
||||
json!({
|
||||
"ok": false,
|
||||
"completed": r["completed"],
|
||||
"failed": failed,
|
||||
"rolled_back": rollback && went_back,
|
||||
"undone": r["undone"],
|
||||
"results": results,
|
||||
}),
|
||||
true,
|
||||
)
|
||||
}
|
||||
Some(failed) => (
|
||||
json!({
|
||||
"ok": false,
|
||||
"completed": r["completed"],
|
||||
"failed": failed,
|
||||
"rolled_back": rollback,
|
||||
"undone": r["undone"],
|
||||
"results": results,
|
||||
}),
|
||||
true,
|
||||
),
|
||||
};
|
||||
// The app timed the steps where they ran.
|
||||
if let Some(o) = reply.as_object_mut() {
|
||||
|
||||
@@ -63,7 +63,7 @@ pub use profiles::{
|
||||
CurvePick, Profile, distinct_curves, find_drawn_profiles, find_profiles, merge_regions, profile_at_point, profile_by_curves,
|
||||
without_text_counters,
|
||||
};
|
||||
pub use shape::{Shape, intersections, intersections_within};
|
||||
pub use shape::{Shape, intersections};
|
||||
pub use solver::solve_after_edit_with_analysis;
|
||||
pub use solver::{
|
||||
Analysis, CONSISTENT, DrivingValues, Hold, SolveReport, SolveStatus, constraint_residual, determined_by, measure_dimension, move_line_towards,
|
||||
|
||||
@@ -428,19 +428,9 @@ pub(crate) fn draw_row(ui: &mut egui::Ui, id: egui::Id, row: &Row) -> RowResp {
|
||||
if row.selected { crate::theme::TabAccent::current(ui.ctx()).ink } else { row.color.unwrap_or(if row.dim { t.text_dim } else { t.text }) };
|
||||
let label_display = if row.name { crate::i18n::tr_name(row.label) } else { crate::i18n::tr_dyn(row.label) };
|
||||
let font = if row.selected { crate::fonts::semibold(t.font_label) } else { FontId::proportional(t.font_label) };
|
||||
// The label stops before the badges and the card's edge; a longer name ends in an ellipsis
|
||||
// and its full text is in the tooltip.
|
||||
let badges_width = row.badges.len() as f32 * 15.0;
|
||||
let room = (r.right() - 4.0 - badges_width - x).max(0.0);
|
||||
let mut job = egui::text::LayoutJob::simple(label_display.to_string(), font, col, room);
|
||||
job.wrap.max_rows = 1;
|
||||
job.wrap.break_anywhere = true;
|
||||
job.wrap.overflow_character = Some('\u{2026}');
|
||||
let galley = ui.painter().layout_job(job);
|
||||
let galley = ui.painter().layout_no_wrap(label_display, font, col);
|
||||
let lw = galley.size().x;
|
||||
let elided = galley.elided;
|
||||
crate::scenario::publish_rect(&format!("row_label:{}", row.label), Rect::from_min_size(pos2(x, cy - galley.size().y / 2.0), galley.size()));
|
||||
ui.painter().with_clip_rect(ui.painter().clip_rect().intersect(r)).galley(pos2(x, cy - galley.size().y / 2.0), galley, col);
|
||||
ui.painter().galley(pos2(x, cy - galley.size().y / 2.0), galley, col);
|
||||
let mut bx = (x + lw + 6.0).min(r.right() - 16.0);
|
||||
for b in row.badges {
|
||||
let br = Rect::from_center_size(pos2(bx + 6.0, cy), vec2(12.0, 12.0));
|
||||
@@ -456,7 +446,6 @@ pub(crate) fn draw_row(ui: &mut egui::Ui, id: egui::Id, row: &Row) -> RowResp {
|
||||
};
|
||||
let resp = match tip {
|
||||
Some(t) => resp.on_hover_text(t),
|
||||
None if elided => resp.on_hover_text(label_display.to_string()),
|
||||
None => resp,
|
||||
};
|
||||
out.on_control = press_on != 0;
|
||||
@@ -1248,7 +1237,7 @@ fn origin_rows(app: &mut SolveApp, ui: &mut egui::Ui, depth: usize, acts: &Actio
|
||||
let sel = match icon {
|
||||
"plane" => Some(Sel::Plane { name: k.into() }),
|
||||
"axis" => Some(Sel::Axis { name: k.into() }),
|
||||
_ => Some(Sel::Vertex { body: String::new(), point: solidcraft_engine::geom::Vec3::ZERO }),
|
||||
_ => None,
|
||||
};
|
||||
let (selected, mark) = lit_row(lit(&thing));
|
||||
let r = draw_row(
|
||||
@@ -1568,8 +1557,6 @@ fn pick_from_browser(app: &mut SolveApp, x: Sel) {
|
||||
let hit = match &x {
|
||||
Sel::Plane { name } => crate::viewport::Hit::Plane { name: name.clone(), point: solidcraft_engine::geom::Vec3::ZERO },
|
||||
Sel::Axis { name } => crate::viewport::Hit::Axis { name: name.clone() },
|
||||
// The origin point goes only into a dialog input that takes it.
|
||||
Sel::Vertex { body, point } if body.is_empty() && app.dialog.is_some() => crate::viewport::Hit::Vertex { body: String::new(), point: *point },
|
||||
_ => return,
|
||||
};
|
||||
if let Some(mut d) = app.dialog.take() {
|
||||
|
||||
@@ -239,16 +239,3 @@ fn browser_width_rejects_hostile_preferences_and_tiny_windows_still_fit() {
|
||||
assert!(available.contains_rect(bounds));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_body_name_stays_inside_the_card_and_ends_in_an_ellipsis() {
|
||||
let mut h = Harness::new();
|
||||
h.call("ui.resize", json!({"width":1400,"height":900}));
|
||||
let name = "W".repeat(200);
|
||||
h.app.run("solid.box", json!({"body_name":name, "operation":"new", "length":10, "width":10, "height":10})).unwrap();
|
||||
h.settle();
|
||||
let card = rect_of("browser:card").unwrap();
|
||||
let label = rect_of(&format!("row_label:{name}")).expect("the body row is drawn");
|
||||
assert!(label.right() <= card.right(), "{label:?} spills out of {card:?}");
|
||||
assert!(label.width() > 100.0, "the name keeps the room it has: {label:?}");
|
||||
}
|
||||
|
||||
@@ -1,110 +0,0 @@
|
||||
//! Written help for the ribbon tooltips (#2758): two short sentences per command, shown under the
|
||||
//! tool name when the pointer rests on its button. The names stay as they are; the help is a
|
||||
//! separate message `help.<command id>` in the catalogs, so a tool without help keeps its plain
|
||||
//! tooltip. Text only for now; pictures and animations are a later step.
|
||||
|
||||
use crate::i18n;
|
||||
|
||||
/// The commands that have help text. Each one needs a `help.<id>` message in the catalogs.
|
||||
pub const DOCUMENTED: &[&str] = &["solid.chamfer", "solid.extrude", "solid.fillet", "solid.hole", "solid.revolve", "solid.shell"];
|
||||
|
||||
/// The help for `command` in the current language, when it has any.
|
||||
pub fn help(command: &str) -> Option<String> {
|
||||
if !DOCUMENTED.contains(&command) {
|
||||
return None;
|
||||
}
|
||||
let key = format!("help.{command}");
|
||||
let text = i18n::tr(&key);
|
||||
(text != key).then(|| text.to_owned())
|
||||
}
|
||||
|
||||
/// Show `tip` (name, shortcut or the reason the tool is disabled) as the tooltip of `response`,
|
||||
/// with the help of `command` below it when there is one.
|
||||
pub fn tooltip(response: egui::Response, command: &str, tip: String) -> egui::Response {
|
||||
let help = help(command);
|
||||
response.on_hover_ui(move |ui| {
|
||||
ui.set_max_width(300.0);
|
||||
ui.label(tip);
|
||||
if let Some(help) = help {
|
||||
ui.add_space(2.0);
|
||||
ui.label(egui::RichText::new(help).weak());
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The tooltip text of a panel drop-down row: the reason when the command is disabled (as before),
|
||||
/// else its name and shortcut when it has help to show below, else nothing (no tooltip).
|
||||
pub fn row_tip(command: &str, label: &str, shortcut: Option<&str>, disabled_reason: Option<&str>) -> Option<String> {
|
||||
match disabled_reason {
|
||||
Some(why) => Some(why.to_owned()),
|
||||
None => help(command).map(|_| format!("{label}{}", shortcut.map(|k| format!(" ({k})")).unwrap_or_default())),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
fn catalog(source: &str) -> std::collections::BTreeMap<String, String> {
|
||||
serde_json::from_str(source).unwrap()
|
||||
}
|
||||
|
||||
/// The `help.<command id>` messages; other `help.*` messages (About dialog texts) are not tool help.
|
||||
fn help_keys(source: &str) -> BTreeSet<String> {
|
||||
catalog(source)
|
||||
.into_keys()
|
||||
.filter(|k| k.starts_with("help.") && (k.starts_with("help.solid.") || DOCUMENTED.contains(&&k["help.".len()..])))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_documented_id_is_a_real_command() {
|
||||
for id in DOCUMENTED {
|
||||
assert!(solidcraft_engine::find_command(id).is_some(), "{id} is not a command");
|
||||
}
|
||||
assert!(DOCUMENTED.is_sorted());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_help_message_is_for_a_documented_command() {
|
||||
let english = help_keys(include_str!("../../../assets/locales/en.json"));
|
||||
let wanted: BTreeSet<String> = DOCUMENTED.iter().map(|id| format!("help.{id}")).collect();
|
||||
assert_eq!(english, wanted);
|
||||
for key in &english {
|
||||
let id = key.trim_start_matches("help.");
|
||||
assert!(solidcraft_engine::find_command(id).is_some(), "{key} names no command");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_help_texts_are_written_in_every_complete_language() {
|
||||
let english = catalog(include_str!("../../../assets/locales/en.json"));
|
||||
for source in [include_str!("../../../assets/locales/ja.json"), include_str!("../../../assets/locales/zh.json")] {
|
||||
let other = catalog(source);
|
||||
for (key, text) in english.iter().filter(|(k, _)| k.starts_with("help.")) {
|
||||
let translated = other.get(key).unwrap_or_else(|| panic!("{key} missing"));
|
||||
assert!(!translated.trim().is_empty());
|
||||
// The messages carry no placeholders; if one is added, both sides must agree.
|
||||
assert_eq!(text.matches('{').count(), translated.matches('{').count(), "{key}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_documented_command_has_help_and_others_do_not() {
|
||||
for id in DOCUMENTED {
|
||||
assert!(help(id).is_some_and(|text| !text.is_empty()), "{id}");
|
||||
}
|
||||
assert!(help("solid.pattern.rectangular").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_drop_down_row_has_a_tip_only_for_a_reason_or_help() {
|
||||
assert_eq!(row_tip("solid.shell", "Shell", Some("S"), None).as_deref(), Some("Shell (S)"));
|
||||
assert_eq!(row_tip("solid.hole", "Hole", None, None).as_deref(), Some("Hole"));
|
||||
assert_eq!(row_tip("solid.hole", "Hole", None, Some("Select a face")).as_deref(), Some("Select a face"));
|
||||
assert_eq!(row_tip("solid.pattern.rectangular", "Pattern", None, None), None);
|
||||
assert_eq!(row_tip("solid.pattern.rectangular", "Pattern", None, Some("No body")).as_deref(), Some("No body"));
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,7 @@ use solidcraft_engine::geom::Vec3;
|
||||
use crate::SolveApp;
|
||||
use crate::dialogs::{Dialog, Kind};
|
||||
use crate::gizmo::{self, Change, Drag};
|
||||
use crate::selection::{AXES, BODIES, EDGES, FACES, ORIGIN, SelInput, VERTICES};
|
||||
use crate::selection::{AXES, BODIES, EDGES, FACES, SelInput, VERTICES};
|
||||
|
||||
pub const TYPES: [&str; 5] = ["Free Move", "Translate", "Rotate", "Point to Point", "Point to Position"];
|
||||
pub const FREE: usize = 0;
|
||||
@@ -20,7 +20,7 @@ pub const TRANSLATE: usize = 1;
|
||||
pub const ROTATE: usize = 2;
|
||||
pub const POINT_TO_POINT: usize = 3;
|
||||
pub const POINT_TO_POSITION: usize = 4;
|
||||
const POINTS: u16 = VERTICES | FACES | EDGES | ORIGIN;
|
||||
const POINTS: u16 = VERTICES | FACES | EDGES;
|
||||
|
||||
/// A fresh Move dialog of a type (all values zero).
|
||||
pub fn kind(mode: usize) -> Kind {
|
||||
|
||||
@@ -69,33 +69,3 @@ fn every_move_type_has_somewhere_to_put_its_value_box() {
|
||||
assert!(at.is_some(), "{} has nowhere to put its value box", TYPES[mode]);
|
||||
}
|
||||
}
|
||||
|
||||
/// Point to Point takes the origin point as From or To (#3696): a click on the origin dot picks
|
||||
/// it, and the body moves from its corner onto the origin.
|
||||
#[test]
|
||||
fn point_to_point_takes_the_origin_point() {
|
||||
let mut h = crate::scenario::Harness::new();
|
||||
h.app.ui.show_origin = true;
|
||||
h.app.run("solid.box", json!({"length": 20, "width": 20, "height": 20})).unwrap();
|
||||
h.app.run("solid.move", json!({"bodies": ["Body1"], "translate": ["30 mm", "20 mm", "0 mm"]})).unwrap();
|
||||
h.app.cam.distance = 200.0;
|
||||
h.settle();
|
||||
let hi = h.app.session.model.state().body("Body1").unwrap().mesh().bounds().max;
|
||||
h.app.start("solid.move");
|
||||
{
|
||||
let d = h.app.dialog.as_mut().unwrap();
|
||||
d.kind = kind(POINT_TO_POINT);
|
||||
d.inputs = inputs(POINT_TO_POINT);
|
||||
d.inputs[0].items = vec![Sel::Body { name: "Body1".into() }];
|
||||
d.active = 1;
|
||||
}
|
||||
let corner = h.call("ui.at", json!({ "world": [hi.x, hi.y, hi.z] }))["result"].clone();
|
||||
h.step(&json!({ "click": corner })).unwrap();
|
||||
h.app.dialog.as_mut().unwrap().active = 2;
|
||||
let origin = h.call("ui.at", json!({ "world": [0, 0, 0] }))["result"].clone();
|
||||
h.step(&json!({ "click": origin })).unwrap();
|
||||
let d = h.app.dialog.clone().unwrap();
|
||||
assert_eq!(d.inputs[2].items, vec![Sel::Vertex { body: String::new(), point: Vec3::ZERO }], "the origin is the To point");
|
||||
let p = params(&h.app, &d).unwrap();
|
||||
assert_eq!(p["translate"], json!([mm(-hi.x), mm(-hi.y), mm(-hi.z)]), "the corner goes onto the origin");
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! The Save as mesh dialog (`file.save_mesh`): which bodies, the mesh format, and optionally a
|
||||
//! slicer to open the saved file in.
|
||||
//!
|
||||
//! Every place that saves a mesh opens this dialog: File › Export STL / Export 3MF, the Mesh tab, and the
|
||||
//! Every place that saves a mesh opens this dialog: File › Save as mesh, the Mesh tab, and the
|
||||
//! Save As Mesh item of the body menus. The slicer list holds the programs the user added (kept
|
||||
//! between runs, newest first), then the slicers found on this machine, then "Custom…", which asks
|
||||
//! for a program and adds it at the top; "Custom…" itself is never the selection. Pressing Delete
|
||||
@@ -39,14 +39,6 @@ pub struct SaveMesh {
|
||||
stale: bool,
|
||||
}
|
||||
|
||||
impl SaveMesh {
|
||||
/// The chosen format, as `file.save_mesh` names it (`stl`, `3mf`, `3mf-tagged`).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn format_name(&self) -> &'static str {
|
||||
FORMATS.get(self.format).map_or("stl", |f| f.1)
|
||||
}
|
||||
}
|
||||
|
||||
/// One line of the slicer list.
|
||||
struct Entry {
|
||||
key: String,
|
||||
@@ -95,17 +87,6 @@ pub fn start(app: &SolveApp, id: &str) -> Option<(Kind, Vec<SelInput>)> {
|
||||
Some((kind, vec![SelInput::new("Bodies", BODIES, true)]))
|
||||
}
|
||||
|
||||
/// Open the dialog with `format` (`stl`, `3mf` or `3mf-tagged`) chosen, whatever was used last:
|
||||
/// File › Export STL… and Export 3MF…. The user can still change it in the dialog.
|
||||
pub fn start_with_format(app: &mut SolveApp, format: &str) {
|
||||
app.start("file.save_mesh");
|
||||
if let Some(index) = FORMATS.iter().position(|f| f.1 == format)
|
||||
&& let Some(Kind::SaveMesh(k)) = app.dialog.as_mut().map(|d| &mut d.kind)
|
||||
{
|
||||
k.format = index;
|
||||
}
|
||||
}
|
||||
|
||||
/// A popup with the slicer list is open (Delete belongs to it, not to the design's selection).
|
||||
pub fn popup_open(ctx: &egui::Context) -> bool {
|
||||
let frame = ctx.cumulative_frame_nr();
|
||||
|
||||
@@ -18,9 +18,7 @@ pub const MAX_OPEN: usize = 32;
|
||||
|
||||
/// A design that is not the active one: everything that belongs to it alone.
|
||||
pub struct DocSlot {
|
||||
pub(crate) session: Session,
|
||||
pub(crate) autosave: Option<solidcraft_engine::recovery::Autosaver>,
|
||||
pub(crate) big_operation: bool,
|
||||
session: Session,
|
||||
cam: Camera,
|
||||
pre_sketch_cam: Option<Camera>,
|
||||
pre_sketch_marker: Option<Option<usize>>,
|
||||
@@ -40,16 +38,7 @@ struct DocView {
|
||||
|
||||
impl DocSlot {
|
||||
fn new(session: Session) -> DocSlot {
|
||||
DocSlot {
|
||||
session,
|
||||
autosave: None,
|
||||
big_operation: false,
|
||||
cam: Camera::default(),
|
||||
pre_sketch_cam: None,
|
||||
pre_sketch_marker: None,
|
||||
view: DocView::default(),
|
||||
occurrence_move: None,
|
||||
}
|
||||
DocSlot { session, cam: Camera::default(), pre_sketch_cam: None, pre_sketch_marker: None, view: DocView::default(), occurrence_move: None }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,17 +55,9 @@ pub struct Documents {
|
||||
pub choice: Answer,
|
||||
/// Save As is answering a Close/Quit prompt.
|
||||
saving: bool,
|
||||
/// Close Other Tabs / Close All Tabs: the tabs still to close, in increasing order (the last
|
||||
/// is closed first, so the ones before it keep their places). One with unsaved changes asks
|
||||
/// first; Cancel stops the rest (#3055).
|
||||
pub batch: Option<Vec<usize>>,
|
||||
}
|
||||
|
||||
impl Documents {
|
||||
pub(crate) fn background_mut(&mut self) -> impl Iterator<Item = &mut DocSlot> {
|
||||
self.slots.iter_mut().filter_map(Option::as_mut)
|
||||
}
|
||||
|
||||
/// Number of open designs (at least the active one).
|
||||
pub fn count(&self) -> usize {
|
||||
self.slots.len().max(1)
|
||||
@@ -126,19 +107,14 @@ fn swap_in(app: &mut SolveApp, slot: DocSlot) -> DocSlot {
|
||||
app.menu.props = None;
|
||||
crate::sketch_attachment_ui::clear(app);
|
||||
let out_rev = app.session.revision;
|
||||
let mut out = DocSlot {
|
||||
let out = DocSlot {
|
||||
session: std::mem::replace(&mut app.session, slot.session),
|
||||
autosave: app.autosave.as_mut().and_then(|a| std::mem::replace(&mut a.active, slot.autosave)),
|
||||
big_operation: std::mem::replace(&mut app.big_operation, slot.big_operation),
|
||||
cam: std::mem::replace(&mut app.cam, slot.cam),
|
||||
pre_sketch_cam: std::mem::replace(&mut app.pre_sketch_cam, slot.pre_sketch_cam),
|
||||
pre_sketch_marker: std::mem::replace(&mut app.pre_sketch_marker, slot.pre_sketch_marker),
|
||||
view: take_view(app),
|
||||
occurrence_move: std::mem::replace(&mut app.tree.occurrence_move, slot.occurrence_move),
|
||||
};
|
||||
// Only the displayed design owns the process-wide crash replay journal.
|
||||
app.session.crash_journal = out.session.crash_journal;
|
||||
out.session.crash_journal = false;
|
||||
put_view(app, slot.view);
|
||||
// Preferences the session holds go with the user, not the tab (#680).
|
||||
app.session.auto_project = out.session.auto_project;
|
||||
@@ -278,10 +254,6 @@ pub fn close(app: &mut SolveApp, i: usize, force: bool) {
|
||||
app.docs.closing = None;
|
||||
if n <= 1 {
|
||||
// The last design: a blank one takes its place.
|
||||
if let Some(a) = app.autosave.as_mut().and_then(|a| a.active.take()) {
|
||||
a.discard();
|
||||
}
|
||||
app.big_operation = false;
|
||||
crate::sketch_text_move::cancel_drag(app);
|
||||
let rev = app.session.revision;
|
||||
crate::dialogs::cancel(app);
|
||||
@@ -301,47 +273,12 @@ pub fn close(app: &mut SolveApp, i: usize, force: bool) {
|
||||
let next = if i + 1 < n { i + 1 } else { i - 1 };
|
||||
switch(app, next);
|
||||
}
|
||||
if let Some(slot) = app.docs.slots.remove(i)
|
||||
&& let Some(a) = slot.autosave
|
||||
{
|
||||
a.discard();
|
||||
}
|
||||
app.docs.slots.remove(i);
|
||||
if app.docs.active > i {
|
||||
app.docs.active -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// Close several tabs (Close Other Tabs, Close All Tabs; #3055): each with unsaved changes asks
|
||||
/// "save changes?" in turn, the others close; Cancel keeps the tabs not closed yet.
|
||||
pub fn close_many(app: &mut SolveApp, mut tabs: Vec<usize>) {
|
||||
if app.file_picker_busy() || app.docs.quitting.is_some() || app.docs.closing.is_some() {
|
||||
return;
|
||||
}
|
||||
tabs.sort_unstable();
|
||||
tabs.dedup();
|
||||
app.docs.batch = Some(tabs);
|
||||
batch_step(app);
|
||||
}
|
||||
|
||||
/// Close the next tab of [`close_many`]'s batch, or ask about it when it has unsaved changes.
|
||||
fn batch_step(app: &mut SolveApp) {
|
||||
if app.docs.closing.is_some() || app.docs.quitting.is_some() {
|
||||
return;
|
||||
}
|
||||
let Some(mut left) = app.docs.batch.take() else { return };
|
||||
while let Some(i) = left.pop() {
|
||||
if i >= app.docs.count() {
|
||||
continue;
|
||||
}
|
||||
if dirty(app, i) {
|
||||
app.docs.closing = Some(i);
|
||||
app.docs.batch = Some(left);
|
||||
return;
|
||||
}
|
||||
close(app, i, true);
|
||||
}
|
||||
}
|
||||
|
||||
/// Quit (the title bar's ×, File ▸ Quit, the window being closed): asks "save changes?" for each
|
||||
/// design with unsaved changes, then sets `app.quit_requested` for the host to close the window.
|
||||
/// Cancel, or a Save that didn't save, stays open.
|
||||
@@ -406,19 +343,13 @@ pub fn tabs_info(app: &SolveApp) -> Vec<(String, bool)> {
|
||||
}
|
||||
|
||||
/// The control channel's `ui.documents`: list, `new`, `switch`, `close` (by index; `force`
|
||||
/// closes without asking), `close_others` (all but `index`), `close_all` or `quit`; `answer`:
|
||||
/// save | dont_save | cancel answers "save changes?".
|
||||
/// closes without asking) or `quit`; `answer`: save | dont_save | cancel answers "save changes?".
|
||||
pub fn control(app: &mut SolveApp, p: &Value) -> Value {
|
||||
let i = p.get("index").and_then(Value::as_u64).map(|x| x as usize);
|
||||
match p.get("action").and_then(Value::as_str) {
|
||||
Some("new") => new_design(app),
|
||||
Some("switch") => switch(app, i.unwrap_or(app.docs.active)),
|
||||
Some("close") => close(app, i.unwrap_or(app.docs.active), p.get("force").and_then(Value::as_bool).unwrap_or(false)),
|
||||
Some("close_others") => {
|
||||
let keep = i.unwrap_or(app.docs.active);
|
||||
close_many(app, (0..app.docs.count()).filter(|k| *k != keep).collect());
|
||||
}
|
||||
Some("close_all") => close_many(app, (0..app.docs.count()).collect()),
|
||||
Some("quit") => request_quit(app),
|
||||
_ => {}
|
||||
}
|
||||
@@ -432,7 +363,7 @@ pub fn control(app: &mut SolveApp, p: &Value) -> Value {
|
||||
answer_prompt(app, a);
|
||||
}
|
||||
let tabs: Vec<Value> = tabs_info(app).into_iter().map(|(name, dirty)| json!({"name": name, "dirty": dirty})).collect();
|
||||
json!({"documents": tabs, "active": app.docs.active, "closing": app.docs.closing, "quitting": app.docs.quitting.is_some(), "batch": app.docs.batch})
|
||||
json!({"documents": tabs, "active": app.docs.active, "closing": app.docs.closing, "quitting": app.docs.quitting.is_some()})
|
||||
}
|
||||
|
||||
/// The document tabs in the application bar, from `x0` to `x1`: click to switch, × to close,
|
||||
@@ -457,9 +388,6 @@ pub fn tabs(app: &mut SolveApp, ui: &mut egui::Ui, r: Rect, x0: f32, x1: f32) {
|
||||
})
|
||||
.collect();
|
||||
let fit_all = shown == n && natural.iter().sum::<f32>() <= x1 - x0 - 34.0;
|
||||
// A right-click on a tab opens its menu (#3055): the tab and where the menu opens.
|
||||
let menu_id = egui::Id::new("sc_doc_tab_menu");
|
||||
let mut menu: Option<(usize, egui::Pos2)> = ui.ctx().data(|d| d.get_temp(menu_id));
|
||||
for (i, (name, dirty)) in info.iter().enumerate().skip(first).take(shown) {
|
||||
let w = if fit_all { natural.get(i).copied().unwrap_or(w) } else { w };
|
||||
let tr = Rect::from_min_size(pos2(x, r.top() + 4.0), vec2(w - 2.0, r.height() - 8.0));
|
||||
@@ -504,9 +432,6 @@ pub fn tabs(app: &mut SolveApp, ui: &mut egui::Ui, r: Rect, x0: f32, x1: f32) {
|
||||
if xresp.hovered() || xresp.has_focus() { 1.0 } else { 0.55 },
|
||||
);
|
||||
}
|
||||
if resp.secondary_clicked() {
|
||||
menu = Some((i, ui.ctx().pointer_interact_pos().unwrap_or(tr.left_bottom())));
|
||||
}
|
||||
if xresp.on_hover_text("Close").clicked() {
|
||||
shut = Some(i);
|
||||
} else if resp.on_hover_text(name.as_str()).clicked() {
|
||||
@@ -552,44 +477,6 @@ pub fn tabs(app: &mut SolveApp, ui: &mut egui::Ui, r: Rect, x0: f32, x1: f32) {
|
||||
}
|
||||
x += 26.0;
|
||||
}
|
||||
// The tab's menu: close it, the others, or all of them.
|
||||
let mut many: Option<Vec<usize>> = None;
|
||||
if let Some((i, at)) = menu.filter(|(i, _)| *i < n) {
|
||||
let items = [("ui.closeTab", "Close"), ("ui.closeOtherTabs", "Close Other Tabs"), ("ui.closeAllTabs", "Close All Tabs")];
|
||||
let resp = crate::frame::area(menu_id.with("area")).fixed_pos(at).order(egui::Order::Foreground).show(ui.ctx(), |ui| {
|
||||
crate::context_menu::menu_frame(ui, |ui| {
|
||||
let mut chosen = None;
|
||||
for (id, label) in items {
|
||||
let mut item = crate::context_menu::Item::action(id, label, "");
|
||||
item.enabled = id != "ui.closeOtherTabs" || n > 1;
|
||||
let top = ui.cursor().top();
|
||||
let row = crate::context_menu::list_row(ui, &item);
|
||||
let rect = Rect::from_min_max(pos2(ui.min_rect().left(), top), pos2(ui.min_rect().right(), ui.cursor().top()));
|
||||
crate::scenario::publish_handle(&format!("tab_menu:{id}"), rect.center());
|
||||
if row.is_some() {
|
||||
chosen = Some(id);
|
||||
}
|
||||
}
|
||||
chosen
|
||||
})
|
||||
});
|
||||
match resp.inner {
|
||||
Some("ui.closeTab") => shut = Some(i),
|
||||
Some("ui.closeOtherTabs") => many = Some((0..n).filter(|k| *k != i).collect()),
|
||||
Some("ui.closeAllTabs") => many = Some((0..n).collect()),
|
||||
_ => {}
|
||||
}
|
||||
let pressed_outside = ui.ctx().input(|x| x.pointer.any_pressed()) && !resp.response.contains_pointer();
|
||||
menu = if resp.inner.is_some() || pressed_outside || ui.ctx().input(|x| x.key_pressed(egui::Key::Escape)) { None } else { Some((i, at)) };
|
||||
}
|
||||
ui.ctx().data_mut(|d| match menu {
|
||||
Some(m) => {
|
||||
d.insert_temp(menu_id, m);
|
||||
}
|
||||
None => {
|
||||
d.remove::<(usize, egui::Pos2)>(menu_id);
|
||||
}
|
||||
});
|
||||
// New design: a new tab showing the start page.
|
||||
let pr = Rect::from_center_size(pos2(x + 14.0, r.center().y), vec2(22.0, 22.0));
|
||||
let presp = ui.interact(pr, ui.id().with("doc_new"), Sense::click());
|
||||
@@ -609,7 +496,6 @@ pub fn tabs(app: &mut SolveApp, ui: &mut egui::Ui, r: Rect, x0: f32, x1: f32) {
|
||||
}
|
||||
match (shut, pick) {
|
||||
_ if !idle => {}
|
||||
_ if many.is_some() => close_many(app, many.unwrap_or_default()),
|
||||
(Some(i), _) => close(app, i, false),
|
||||
(None, Some(i)) => switch(app, i),
|
||||
(None, None) => {}
|
||||
@@ -739,11 +625,9 @@ pub fn answer_prompt(app: &mut SolveApp, answer: Answer) {
|
||||
Answer::Cancel => {
|
||||
app.docs.closing = None;
|
||||
app.docs.quitting = None;
|
||||
app.docs.batch = None;
|
||||
}
|
||||
}
|
||||
quit_step(app);
|
||||
batch_step(app);
|
||||
}
|
||||
|
||||
/// Resume Close/Quit only after Save As has answered and the write succeeded.
|
||||
@@ -759,12 +643,8 @@ pub(crate) fn saved_for_close(app: &mut SolveApp) {
|
||||
}
|
||||
} else if saved {
|
||||
close(app, app.docs.active, true);
|
||||
} else {
|
||||
// Save As cancelled: the tabs not closed yet stay.
|
||||
app.docs.batch = None;
|
||||
}
|
||||
quit_step(app);
|
||||
batch_step(app);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -824,68 +704,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Four tabs: the first and third with a part (unsaved), the second and fourth blank.
|
||||
fn four_tabs() -> SolveApp {
|
||||
let mut a = app();
|
||||
a.run("solid.box", json!({"length": 10, "width": 10, "height": 10})).unwrap();
|
||||
open_tab(&mut a, Session::default()).unwrap();
|
||||
open_tab(&mut a, Session::default()).unwrap();
|
||||
a.run("solid.box", json!({"length": 5, "width": 5, "height": 5})).unwrap();
|
||||
open_tab(&mut a, Session::default()).unwrap();
|
||||
assert_eq!(a.docs.count(), 4);
|
||||
a
|
||||
}
|
||||
|
||||
/// #3055: Close Other Tabs on the first tab closes the blank fourth, asks about the third
|
||||
/// (unsaved), and after Don't Save closes it and the blank second: the first is left, its
|
||||
/// part as it was.
|
||||
#[test]
|
||||
fn close_other_tabs_asks_about_unsaved_ones_and_keeps_the_tab() {
|
||||
let mut a = four_tabs();
|
||||
let v = control(&mut a, &json!({"action": "close_others", "index": 0}));
|
||||
assert_eq!(v["closing"], json!(2), "{v}");
|
||||
assert_eq!(a.docs.count(), 3, "the blank fourth closed without asking");
|
||||
let v = control(&mut a, &json!({"answer": "dont_save"}));
|
||||
assert_eq!(a.docs.count(), 1, "{v}");
|
||||
assert!(a.docs.closing.is_none() && a.docs.batch.is_none());
|
||||
let volume = a.run("inspect.measure", json!({})).unwrap()["total"]["volume_mm3"].as_f64().unwrap();
|
||||
assert!((volume - 1000.0).abs() < 1e-6, "the first tab's part: {volume}");
|
||||
}
|
||||
|
||||
/// #3055: Close All Tabs, and Cancel at the first question: the tabs not closed yet stay.
|
||||
/// Close All Tabs on blank designs leaves one blank design.
|
||||
#[test]
|
||||
fn close_all_tabs_stops_at_cancel_and_ends_on_a_blank_design() {
|
||||
let mut a = four_tabs();
|
||||
control(&mut a, &json!({"action": "close_all"}));
|
||||
assert_eq!((a.docs.count(), a.docs.closing), (3, Some(2)));
|
||||
control(&mut a, &json!({"answer": "cancel"}));
|
||||
assert_eq!((a.docs.count(), a.docs.closing, a.docs.batch.clone()), (3, None, None), "Cancel keeps the rest");
|
||||
control(&mut a, &json!({"action": "close_all"}));
|
||||
control(&mut a, &json!({"answer": "dont_save"}));
|
||||
control(&mut a, &json!({"answer": "dont_save"}));
|
||||
assert_eq!(a.docs.count(), 1);
|
||||
assert!(active_is_blank(&a), "all closed: a blank design");
|
||||
}
|
||||
|
||||
/// #3055: a right-click on a tab opens its menu; Close Other Tabs from it keeps that tab.
|
||||
#[test]
|
||||
fn a_tab_right_clicked_offers_close_others() {
|
||||
let mut h = crate::scenario::Harness::new();
|
||||
h.app.home.open = false;
|
||||
h.app.custom_titlebar = true;
|
||||
h.call("ui.resize", json!({"width": 1400, "height": 720}));
|
||||
open_tab(&mut h.app, Session::default()).unwrap();
|
||||
open_tab(&mut h.app, Session::default()).unwrap();
|
||||
assert_eq!(h.app.docs.count(), 3);
|
||||
h.frames(3);
|
||||
h.step(&json!({"click": {"handle": "tab:design:1"}, "button": "right"})).unwrap();
|
||||
h.frames(2);
|
||||
h.step(&json!({"click": {"handle": "tab_menu:ui.closeOtherTabs"}})).unwrap();
|
||||
h.frames(2);
|
||||
assert_eq!(h.app.docs.count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tabs_keep_their_own_design() {
|
||||
let mut a = app();
|
||||
|
||||
@@ -164,7 +164,7 @@ pub fn with_symbol_fallback(mut fonts: egui::FontDefinitions) -> egui::FontDefin
|
||||
|
||||
/// UI languages whose text needs the CJK font. The web app's bundled font covers Japanese only;
|
||||
/// add Chinese or Korean here together with a font that covers them.
|
||||
pub const CJK_LANGUAGES: &[&str] = &["ja", "zh", "zh-TW", "ko"];
|
||||
pub const CJK_LANGUAGES: &[&str] = &["ja", "zh", "ko"];
|
||||
|
||||
/// Whether the UI language needs a CJK font (the web app fetches one only then).
|
||||
pub fn needs_cjk_font(language: &str) -> bool {
|
||||
@@ -648,7 +648,7 @@ fn find_system_cjk_font() -> Option<Vec<u8>> {
|
||||
/// Thai comes last whatever the language: no other face draws it.
|
||||
pub fn fallback_order(language: &str) -> [&'static str; 4] {
|
||||
match language {
|
||||
"zh" | "zh-TW" => [CHINESE_FALLBACK, CJK_FALLBACK, HANGUL_FALLBACK, THAI_FALLBACK],
|
||||
"zh" => [CHINESE_FALLBACK, CJK_FALLBACK, HANGUL_FALLBACK, THAI_FALLBACK],
|
||||
"ko" => [HANGUL_FALLBACK, CJK_FALLBACK, CHINESE_FALLBACK, THAI_FALLBACK],
|
||||
_ => [CJK_FALLBACK, CHINESE_FALLBACK, HANGUL_FALLBACK, THAI_FALLBACK],
|
||||
}
|
||||
@@ -991,7 +991,6 @@ mod tests {
|
||||
#[test]
|
||||
fn a_chinese_ui_puts_the_chinese_face_before_the_japanese_one() {
|
||||
assert_eq!(fallback_order("zh"), [CHINESE_FALLBACK, CJK_FALLBACK, HANGUL_FALLBACK, THAI_FALLBACK]);
|
||||
assert_eq!(fallback_order("zh-TW"), fallback_order("zh"));
|
||||
assert_eq!(fallback_order("ko"), [HANGUL_FALLBACK, CJK_FALLBACK, CHINESE_FALLBACK, THAI_FALLBACK]);
|
||||
for lang in ["en", "ja", "de"] {
|
||||
assert_eq!(
|
||||
|
||||
@@ -425,17 +425,8 @@ pub fn open_sample(app: &mut SolveApp, i: usize) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Is this recent design there to open: in memory, or something the host can bring back?
|
||||
pub fn available(app: &SolveApp, path: &str) -> bool {
|
||||
solidcraft_engine::io::vfs::exists(path) || app.services.can_restore.as_ref().is_some_and(|can| can(path))
|
||||
}
|
||||
|
||||
pub fn open_recent(app: &mut SolveApp, path: &str) {
|
||||
if !solidcraft_engine::io::vfs::exists(path) {
|
||||
if let Some(restore) = app.services.restore_file.as_ref().filter(|_| available(app, path)) {
|
||||
restore(path);
|
||||
return;
|
||||
}
|
||||
app.set_status(format!("{path} is no longer there"), true);
|
||||
return;
|
||||
}
|
||||
@@ -538,12 +529,9 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
let Some(p) = recent.get(i) else { return };
|
||||
let path = std::path::Path::new(p);
|
||||
let name = path.file_stem().map(|x| x.to_string_lossy().to_string()).unwrap_or_else(|| p.clone());
|
||||
let missing = !available(app, p);
|
||||
let missing = !solidcraft_engine::io::vfs::exists(p);
|
||||
let mut sub = if missing {
|
||||
app.tr("home.missing").to_string()
|
||||
} else if p.starts_with("/disk/") {
|
||||
// The web build remembers files it saved on the computer.
|
||||
crate::i18n::tr_label("On your computer").to_string()
|
||||
} else if p.starts_with("/opfs/") {
|
||||
// The web build keeps designs in the browser's own storage.
|
||||
app.tr("home.in_this_browser").to_string()
|
||||
@@ -707,24 +695,6 @@ mod tests {
|
||||
assert!(sample_picture(samples.len()).is_none());
|
||||
}
|
||||
|
||||
/// A recent design the host can bring back (the browser build's remembered files) is not
|
||||
/// "missing": choosing it asks the host to restore it, and one the host doesn't know still is.
|
||||
#[test]
|
||||
fn a_recent_design_the_host_can_restore_is_asked_for_not_reported_missing() {
|
||||
let mut h = crate::scenario::Harness::new();
|
||||
let asked = std::rc::Rc::new(std::cell::RefCell::new(Vec::<String>::new()));
|
||||
let sink = asked.clone();
|
||||
h.app.services.can_restore = Some(Box::new(|p| p.starts_with("/disk/known/")));
|
||||
h.app.services.restore_file = Some(Box::new(move |p| sink.borrow_mut().push(p.to_string())));
|
||||
assert!(available(&h.app, "/disk/known/Bracket.solidcraft"));
|
||||
assert!(!available(&h.app, "/disk/other/Bracket.solidcraft"));
|
||||
open_recent(&mut h.app, "/disk/known/Bracket.solidcraft");
|
||||
assert_eq!(*asked.borrow(), ["/disk/known/Bracket.solidcraft"]);
|
||||
open_recent(&mut h.app, "/disk/other/Bracket.solidcraft");
|
||||
assert_eq!(asked.borrow().len(), 1, "a file the host doesn't remember is not asked for");
|
||||
assert!(h.app.status.as_ref().is_some_and(|(text, _, error)| *error && text.contains("no longer there")));
|
||||
}
|
||||
|
||||
/// Rebuild the shipped pictures from the authoritative sample command scripts.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
|
||||
@@ -35,32 +35,21 @@ static ENGLISH: Catalog = Catalog::new("en", "English", include_str!(concat!(env
|
||||
static CZECH: Catalog = Catalog::new("cs", "Čeština", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/cs.json")));
|
||||
static DANISH: Catalog = Catalog::new("da", "Dansk", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/da.json")));
|
||||
static GERMAN: Catalog = Catalog::new("de", "Deutsch", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/de.json")));
|
||||
/// English in UK spelling: only the messages whose spelling differs; the rest are English's.
|
||||
static ENGLISH_UK: Catalog =
|
||||
Catalog::new("en-GB", "English (UK)", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/en-GB.json")));
|
||||
static SPANISH: Catalog = Catalog::new("es", "Español (España)", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/es.json")));
|
||||
static FRENCH: Catalog = Catalog::new("fr", "Français", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/fr.json")));
|
||||
static GALICIAN: Catalog = Catalog::new("gl", "Galego", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/gl.json")));
|
||||
static HUNGARIAN: Catalog = Catalog::new("hu", "Magyar", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/hu.json")));
|
||||
static INDONESIAN: Catalog =
|
||||
Catalog::new("id", "Bahasa Indonesia", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/id.json")));
|
||||
static ITALIAN: Catalog = Catalog::new("it", "Italiano", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/it.json")));
|
||||
static JAPANESE: Catalog = Catalog::new("ja", "日本語", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/ja.json")));
|
||||
static KOREAN: Catalog = Catalog::new("ko", "한국어", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/ko.json")));
|
||||
static MALAY: Catalog = Catalog::new("ms", "Bahasa Melayu", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/ms.json")));
|
||||
static DUTCH: Catalog = Catalog::new("nl", "Nederlands", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/nl.json")));
|
||||
static POLISH: Catalog = Catalog::new("pl", "Polski", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/pl.json")));
|
||||
static PORTUGUESE_BR: Catalog =
|
||||
Catalog::new("pt-BR", "Português (Brasil)", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/pt-BR.json")));
|
||||
static ROMANIAN: Catalog = Catalog::new("ro", "Română", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/ro.json")));
|
||||
static RUSSIAN: Catalog = Catalog::new("ru", "Русский", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/ru.json")));
|
||||
static SWEDISH: Catalog = Catalog::new("sv", "Svenska", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/sv.json")));
|
||||
static TURKISH: Catalog = Catalog::new("tr", "Türkçe", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/tr.json")));
|
||||
static UKRAINIAN: Catalog = Catalog::new("uk", "Українська", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/uk.json")));
|
||||
static VIETNAMESE: Catalog = Catalog::new("vi", "Tiếng Việt", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/vi.json")));
|
||||
static CHINESE: Catalog = Catalog::new("zh", "中文", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/zh.json")));
|
||||
static CHINESE_TRADITIONAL: Catalog =
|
||||
Catalog::new("zh-TW", "繁體中文", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/zh-TW.json")));
|
||||
/// English first (the fallback), then by language id, one per line so that adding a language
|
||||
/// doesn't edit a line another addition edits.
|
||||
#[rustfmt::skip]
|
||||
@@ -69,27 +58,20 @@ pub const LOCALES: &[&Catalog] = &[
|
||||
&CZECH,
|
||||
&DANISH,
|
||||
&GERMAN,
|
||||
&ENGLISH_UK,
|
||||
&SPANISH,
|
||||
&FRENCH,
|
||||
&GALICIAN,
|
||||
&HUNGARIAN,
|
||||
&INDONESIAN,
|
||||
&ITALIAN,
|
||||
&JAPANESE,
|
||||
&KOREAN,
|
||||
&MALAY,
|
||||
&DUTCH,
|
||||
&POLISH,
|
||||
&PORTUGUESE_BR,
|
||||
&ROMANIAN,
|
||||
&RUSSIAN,
|
||||
&SWEDISH,
|
||||
&TURKISH,
|
||||
&UKRAINIAN,
|
||||
&VIETNAMESE,
|
||||
&CHINESE,
|
||||
&CHINESE_TRADITIONAL,
|
||||
];
|
||||
|
||||
pub fn is_supported(id: &str) -> bool {
|
||||
@@ -256,18 +238,6 @@ mod tests {
|
||||
assert!(ids[1..].is_sorted(), "{ids:?}");
|
||||
}
|
||||
|
||||
/// English (UK) holds only the messages it spells differently; the rest are English's.
|
||||
#[test]
|
||||
fn english_uk_shows_uk_spelling_and_english_for_the_rest() {
|
||||
let (uk, english) = (Locale::for_language("en-GB"), Locale::for_language("en"));
|
||||
assert_eq!(uk.name(), "English (UK)");
|
||||
assert_eq!(uk.label("Center X"), "Centre X");
|
||||
assert_eq!(uk.label("Customize Toolbar"), "Customise Toolbar");
|
||||
assert_eq!(uk.text("ui.design_properties.organization"), "Organisation");
|
||||
assert_eq!(uk.text("ui.preferences"), english.text("ui.preferences"));
|
||||
assert_eq!(english.label("Center X"), "Center X");
|
||||
}
|
||||
|
||||
/// A new design's name, `Untitled`, is a default name like `Sketch1`: it shows translated
|
||||
/// wherever the design's name is shown (the tab, the browser's top row, the save prompt).
|
||||
#[test]
|
||||
@@ -745,28 +715,6 @@ mod tests {
|
||||
assert_eq!(vi.dynamic("Sketch of bracket"), "Sketch of bracket");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_languages_translate_keys_labels_and_default_names() {
|
||||
for (id, name, preferences, extrude, sketch1, save) in [
|
||||
("hu", "Magyar", "Beállítások", "Kihúzás", "Vázlat1", "Menti a(z) My {design} módosításait?"),
|
||||
("id", "Bahasa Indonesia", "Preferensi", "Ekstrusi", "Sketsa1", "Simpan perubahan ke My {design}?"),
|
||||
("nl", "Nederlands", "Voorkeuren", "Extruderen", "Schets1", "Wijzigingen in My {design} opslaan?"),
|
||||
("ro", "Română", "Preferințe", "Extrudare", "Schița1", "Salvați modificările în My {design}?"),
|
||||
("sv", "Svenska", "Inställningar", "Extrudera", "Skiss1", "Spara ändringar i My {design}?"),
|
||||
("zh-TW", "繁體中文", "偏好設定", "擠出", "草圖1", "儲存對 My {design} 的變更?"),
|
||||
] {
|
||||
let locale = Locale::for_language(id);
|
||||
assert_eq!(locale.name(), name);
|
||||
assert!(is_supported(id));
|
||||
assert_eq!(locale.text("ui.preferences"), preferences);
|
||||
assert_eq!(locale.label("Extrude"), extrude);
|
||||
assert_eq!(locale.label("NonExistentKey"), "NonExistentKey");
|
||||
assert_eq!(locale.format("document.save_changes", &[("name", "My {design}")]), save);
|
||||
assert_eq!(locale.dynamic("Sketch1"), sketch1);
|
||||
assert_eq!(locale.dynamic("Sketch of bracket"), "Sketch of bracket");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_scopes_restore_the_previous_language() {
|
||||
let _english = scope("en");
|
||||
|
||||
@@ -20,7 +20,6 @@ pub mod canvas;
|
||||
mod colour_tokens_tests;
|
||||
#[cfg(test)]
|
||||
mod colour_vision_tests;
|
||||
pub mod command_help;
|
||||
pub mod context_menu;
|
||||
pub mod control;
|
||||
pub mod crash_ui;
|
||||
@@ -247,7 +246,7 @@ pub use control::{ControlRequest, ControlResponse};
|
||||
pub struct UiState {
|
||||
/// Automation-only shell mode; never persisted in preferences.
|
||||
pub layout: shell::LayoutMode,
|
||||
/// Ribbon tab; SHEET METAL and the contextual SKETCH join the seven design tabs.
|
||||
/// Ribbon tab; contextual SKETCH and SHEET METAL join the seven design tabs.
|
||||
pub tab: String,
|
||||
/// Last contextual body/sketch, only used to select on entry.
|
||||
#[serde(skip)]
|
||||
@@ -333,12 +332,6 @@ pub struct Services {
|
||||
/// Hand a design's bytes to the user as a downloaded file (name, bytes); the browser build's
|
||||
/// File > Download design. None: the host saves real files, so there is nothing to offer.
|
||||
pub download_design: Option<Box<dyn Fn(&str, &[u8]) -> Result<(), String>>>,
|
||||
/// Whether a recent design that is not in memory can be brought back by the host (the browser
|
||||
/// build remembers files it saved to the disk); None: it can't.
|
||||
pub can_restore: Option<Box<dyn Fn(&str) -> bool>>,
|
||||
/// Bring such a design back and open it when it arrives (asks the user for access, so call it
|
||||
/// in the click that chose it).
|
||||
pub restore_file: Option<Box<dyn Fn(&str)>>,
|
||||
/// Show the designs the browser keeps for itself; None: the host has no such store.
|
||||
pub browser_files: Option<Box<dyn Fn()>>,
|
||||
/// HTTP for the agent chat's API agents (OpenAI-compatible endpoints); None: no API agents.
|
||||
@@ -428,12 +421,10 @@ pub struct SolveApp {
|
||||
pub last_command: Option<(String, String)>,
|
||||
/// Esc was already acted on this frame (by the shortcuts), so later handlers skip it.
|
||||
pub esc_handled: bool,
|
||||
/// When Esc was last pressed (input time): a second press soon after finishes the sketch.
|
||||
pub last_escape: Option<f64>,
|
||||
pub status: Option<(String, f64, bool)>,
|
||||
pub quit_requested: bool,
|
||||
/// Autosave into the recovery folder (the desktop app turns it on).
|
||||
pub autosave: Option<recovery_ui::Autosaves>,
|
||||
pub autosave: Option<solidcraft_engine::recovery::Autosaver>,
|
||||
/// Designs left by crashed apps, offered for recovery.
|
||||
pub recoverable: Vec<solidcraft_engine::recovery::Entry>,
|
||||
/// The bodies of a just-opened Y-up file, offered to be stood up (`stand_up`).
|
||||
@@ -558,7 +549,6 @@ impl SolveApp {
|
||||
apply_gate: None,
|
||||
last_command: None,
|
||||
esc_handled: false,
|
||||
last_escape: None,
|
||||
status: None,
|
||||
quit_requested: false,
|
||||
autosave: None,
|
||||
|
||||
@@ -346,7 +346,7 @@ mod tests {
|
||||
"claims",
|
||||
"moisture_unit",
|
||||
];
|
||||
for catalog in crate::i18n::LOCALES.iter().filter(|c| c.id != "en-GB") {
|
||||
for catalog in crate::i18n::LOCALES {
|
||||
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/locales").join(format!("{}.json", catalog.id));
|
||||
let messages: Value = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
|
||||
for key in keys.into_iter().chain(KINDS) {
|
||||
|
||||
@@ -2173,3 +2173,67 @@ fn hovering_a_large_body_does_not_wait_for_its_pick_index() {
|
||||
assert!(matches!(h.app.viewport.hover, Some(crate::viewport::Hit::Face { .. })), "{:?}", h.app.viewport.hover);
|
||||
assert!(hover_ms < index_ms / 3.0, "the first hover took {hover_ms:.1} ms; making the index takes {index_ms:.1} ms");
|
||||
}
|
||||
|
||||
/// A modelled thread is thousands of small faces but one surface to point at: the pointer over
|
||||
/// it lands on a face (not on the vertices and edges between the thread's own faces), the face
|
||||
/// lights up with the whole thread, and a click selects the thread as one item, which stands for
|
||||
/// every one of its faces when it is shown and when a command takes faces. No hover waits for the
|
||||
/// thread's faces to be worked out.
|
||||
#[test]
|
||||
fn a_modelled_thread_hovers_and_selects_as_one_surface() {
|
||||
let mut h = crate::scenario::Harness::new();
|
||||
h.app.run("solid.cylinder", json!({"diameter": 8, "height": 16, "base": [0, 0, 0], "axis": [0, 0, 1]})).unwrap();
|
||||
h.app.run("solid.thread", json!({"face": [4, 0, 8], "designation": "M8", "length": 10, "modeled": true})).unwrap();
|
||||
let st = h.app.session.world_state();
|
||||
let b = &st.bodies[0];
|
||||
let names = solidcraft_engine::doc::naming::face_names(b);
|
||||
let thread = h.app.session.doc.features.iter().find(|f| matches!(f.kind, solidcraft_engine::doc::FeatureKind::Thread { .. })).unwrap().id;
|
||||
let made = names.iter().filter(|n| n.starts_with(&format!("F{thread}:"))).count();
|
||||
assert!(made > 500, "{made} thread faces");
|
||||
// Close in on the threaded part, side on.
|
||||
h.app.cam.target = Vec3::new(0.0, 0.0, 5.0);
|
||||
h.app.cam.distance = 30.0;
|
||||
h.frames(3);
|
||||
let mut slowest = 0.0f64;
|
||||
let mut grouped = None;
|
||||
for k in 0..40 {
|
||||
let at = h.at(&json!({"world": [4.0 * (0.3 * k as f64).cos(), 4.0 * (0.3 * k as f64).sin(), 2.0 + (k % 6) as f64]})).unwrap();
|
||||
let t = std::time::Instant::now();
|
||||
h.step(&json!({"move": at})).unwrap();
|
||||
slowest = slowest.max(t.elapsed().as_secs_f64() * 1000.0);
|
||||
if let Some(crate::viewport::Hit::Face { body, index, point }) = h.app.viewport.hover.clone() {
|
||||
let sel = Sel::Face { body, index, point };
|
||||
let pieces = crate::viewport::grouped_selection(&h.app.session, &sel);
|
||||
if pieces.len() >= made {
|
||||
grouped = Some(sel);
|
||||
break;
|
||||
}
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
}
|
||||
assert!(slowest < 250.0, "a hover took {slowest:.0} ms");
|
||||
let sel = grouped.expect("hovering the thread lands on its faces, and they are worked out as one surface");
|
||||
// Over the thread, the pointer finds the surface, not the vertices and edges inside it.
|
||||
let faces = (0..12)
|
||||
.filter(|k| {
|
||||
let a = 0.5 * *k as f64;
|
||||
let at = h.at(&json!({"world": [4.0 * a.cos(), 4.0 * a.sin(), 3.0 + (*k % 4) as f64]})).unwrap();
|
||||
h.step(&json!({"move": at})).unwrap();
|
||||
matches!(h.app.viewport.hover, Some(crate::viewport::Hit::Face { .. }))
|
||||
})
|
||||
.count();
|
||||
assert!(faces >= 9, "{faces} of 12 hovers over the thread landed on its surface");
|
||||
// A click selects it as one item, which stands for every face of the thread.
|
||||
let point = match &sel {
|
||||
Sel::Face { point, .. } => *point,
|
||||
_ => Vec3::ZERO,
|
||||
};
|
||||
let at = h.at(&json!({"world": [point.x, point.y, point.z]})).unwrap();
|
||||
let t = std::time::Instant::now();
|
||||
h.step(&json!({"click": at})).unwrap();
|
||||
let click_ms = t.elapsed().as_secs_f64() * 1000.0;
|
||||
assert_eq!(h.app.session.selection.len(), 1, "one item: {:?}", h.app.session.selection.len());
|
||||
let pieces = crate::viewport::grouped_selection(&h.app.session, &h.app.session.selection[0]);
|
||||
assert!(pieces.len() >= made, "the thread stands for {} faces of {made}", pieces.len());
|
||||
assert!(click_ms < 250.0, "the click took {click_ms:.0} ms");
|
||||
}
|
||||
|
||||
@@ -268,9 +268,9 @@ fn motion_key(cmds: &[(String, Value)], revision: u64, colors: Colors) -> Option
|
||||
Some(h.finish())
|
||||
}
|
||||
|
||||
/// Tool previews already stream in `poll`. New-body extrusions, face offsets, fillets and
|
||||
/// chamfers instead build their full result; allow successful intermediate distances (a
|
||||
/// fillet's radii, a chamfer's distances and angle) only within the same setup. Preserve selections, feature identity, extent mode, revision and colours. The
|
||||
/// Tool previews already stream in `poll`. New-body extrusions and face offsets instead
|
||||
/// build their full result; allow successful intermediate distances only within the same
|
||||
/// setup. Preserve selections, feature identity, extent mode, revision and colours. The
|
||||
/// exact job key still ensures the latest distance is computed and errors never go stale.
|
||||
fn stream_key(cmds: &[(String, Value)], revision: u64, colors: Colors) -> Option<u64> {
|
||||
if let Some(key) = motion_key(cmds, revision, colors) {
|
||||
@@ -290,10 +290,6 @@ fn stream_key(cmds: &[(String, Value)], revision: u64, colors: Colors) -> Option
|
||||
let fields: &[&str] = match command.as_str() {
|
||||
"solid.extrude" => &["distance", "distance2", "to_offset"],
|
||||
"solid.offset_face" => &["distance"],
|
||||
// A radius dragged or typed: each result shows while the next computes, rather than
|
||||
// the preview holding still until the input stops changing.
|
||||
"solid.fillet" => &["radius", "radius2", "mid"],
|
||||
"solid.chamfer" => &["distance", "distance2", "angle"],
|
||||
_ => return None,
|
||||
};
|
||||
let params = params.as_object_mut()?;
|
||||
|
||||
@@ -116,11 +116,7 @@ fn distance_stream_keeps_feature_selection_and_extent_context() {
|
||||
assert!(stream_key(&offset(1), 7, colors()).is_some());
|
||||
assert_eq!(stream_key(&offset(1), 7, colors()), stream_key(&offset(5), 7, colors()));
|
||||
assert!(stream_key(&[], 7, colors()).is_none());
|
||||
let fillet = |radius| vec![("solid.fillet".into(), json!({"edges":[[5,0,10]],"radius":radius}))];
|
||||
assert_eq!(stream_key(&fillet(1), 7, colors()), stream_key(&fillet(2), 7, colors()));
|
||||
let other_edge = vec![("solid.fillet".into(), json!({"edges":[[0,5,10]],"radius":1}))];
|
||||
assert_ne!(stream_key(&fillet(1), 7, colors()), stream_key(&other_edge, 7, colors()), "other edges are another setup");
|
||||
assert!(stream_key(&[("solid.shell".into(), json!({"thickness":1}))], 7, colors()).is_none());
|
||||
assert!(stream_key(&[("solid.fillet".into(), json!({"radius":5}))], 7, colors()).is_none());
|
||||
let mut mixed = old;
|
||||
mixed.push(("select.clear".into(), json!({})));
|
||||
assert!(stream_key(&mixed, 7, colors()).is_none());
|
||||
@@ -151,27 +147,3 @@ fn distance_results_reject_other_setups_and_obsolete_errors() {
|
||||
assert!(as_new_body(&join).is_some());
|
||||
assert!(stream_key(&join, s.revision, colors()).is_none(), "tool previews retain their upstream streaming path");
|
||||
}
|
||||
|
||||
/// A fillet's radius dragged (or typed): each finished preview shows while the next radius
|
||||
/// computes, as a distance does; before, every one was dropped until the radius held still.
|
||||
#[test]
|
||||
fn fillet_preview_keeps_moving_while_its_radius_changes() {
|
||||
let mut s = Session::new(solidcraft_engine::doc::Document::new("Fillet drag"));
|
||||
s.execute("solid.box", &json!({"length":10,"width":10,"height":10})).unwrap();
|
||||
let fillet = |radius: i32| vec![("solid.fillet".into(), json!({"edges":[[5,0,10]],"radius":f64::from(radius) / 4.0}))];
|
||||
let mut pv = PreviewState::default();
|
||||
for (finished, wanted) in [(4, 6), (6, 8), (8, 8)] {
|
||||
let (old, new) = (fillet(finished), fillet(wanted));
|
||||
let old_key = job_key(&old, s.revision, colors());
|
||||
let key = job_key(&new, s.revision, colors());
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
pv.running = Some((old_key, rx));
|
||||
pv.running_tool = false;
|
||||
pv.running_stream_key = stream_key(&old, s.revision, colors());
|
||||
tx.send(compute(&s, &old, colors())).unwrap();
|
||||
pv.poll(key, stream_key(&new, s.revision, colors()));
|
||||
assert!(pv.active && pv.error.is_none(), "the finished radius shows during the drag: {:?}", pv.error);
|
||||
assert_eq!(pv.shown_key, Some(old_key));
|
||||
assert!(pv.running.is_none());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,9 +2,6 @@
|
||||
|
||||
use serde_json::json;
|
||||
use solidcraft_engine::recovery::{self, Autosaver, Entry};
|
||||
use solidcraft_engine::{Result, Session};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::SolveApp;
|
||||
use crate::ui_kit;
|
||||
@@ -12,71 +9,11 @@ use crate::ui_kit;
|
||||
/// A command that ran at least this long counts as a big operation: autosave right after it.
|
||||
pub const BIG_OPERATION_MS: f64 = 1500.0;
|
||||
|
||||
/// A tab's autosaver has no clock of its own: [`tick`] tells it when its turn has come.
|
||||
const SHARED_CADENCE: Duration = Duration::MAX;
|
||||
|
||||
/// Shared settings and cadence; each tab owns its own entry and change tracking.
|
||||
pub struct Autosaves {
|
||||
pub dir: PathBuf,
|
||||
pub interval: Duration,
|
||||
pub(crate) active: Option<Autosaver>,
|
||||
last_at: Instant,
|
||||
}
|
||||
|
||||
impl Autosaves {
|
||||
/// Save the active design immediately, including when taking over a recovered entry.
|
||||
pub fn save(&mut self, session: &Session) -> Result<bool> {
|
||||
save_slot(&self.dir, &mut self.active, session, true, true)
|
||||
}
|
||||
}
|
||||
|
||||
/// Bring one tab's autosave up to date. `due`: its turn has come. `wait`: write on this thread
|
||||
/// and wait for it (Save, close, shutdown); otherwise the write runs on a worker thread, so a
|
||||
/// scheduled autosave of several large designs never holds up the window (#3044).
|
||||
fn save_slot(dir: &Path, slot: &mut Option<Autosaver>, session: &Session, due: bool, wait: bool) -> Result<bool> {
|
||||
// Clean tabs need no serialization or entry, even between scheduled saves.
|
||||
if !session.is_dirty() {
|
||||
if let Some(mut a) = slot.take() {
|
||||
// Rebase the active crash journal before deleting the autosave it may refer to.
|
||||
a.save(session)?;
|
||||
a.discard();
|
||||
}
|
||||
return Ok(false);
|
||||
}
|
||||
if !due {
|
||||
return Ok(false);
|
||||
}
|
||||
if slot.is_none() {
|
||||
*slot = Some(Autosaver::new(dir, SHARED_CADENCE)?);
|
||||
}
|
||||
match slot.as_mut() {
|
||||
Some(a) if wait => a.save(session),
|
||||
// Skips a tab whose previous write is still running.
|
||||
Some(a) => a.tick(session, true),
|
||||
None => Ok(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// Autosave every open design on the shared cadence, or a tab after its big operation.
|
||||
/// Autosave (when due, or after a big operation).
|
||||
pub fn tick(app: &mut SolveApp) {
|
||||
let big = std::mem::take(&mut app.big_operation);
|
||||
let Some(a) = app.autosave.as_mut() else { return };
|
||||
let due = a.last_at.elapsed() >= a.interval;
|
||||
if due {
|
||||
a.last_at = Instant::now();
|
||||
}
|
||||
let mut error = None;
|
||||
for slot in app.docs.background_mut() {
|
||||
let big = std::mem::take(&mut slot.big_operation);
|
||||
if let Err(e) = save_slot(&a.dir, &mut slot.autosave, &slot.session, due || big, false) {
|
||||
error.get_or_insert(e);
|
||||
}
|
||||
}
|
||||
// Background writes must not replace the active design's crash-journal checkpoint.
|
||||
if let Err(e) = save_slot(&a.dir, &mut a.active, &app.session, due || big, false) {
|
||||
error.get_or_insert(e);
|
||||
}
|
||||
if let Some(e) = error {
|
||||
if let Err(e) = a.tick(&app.session, big) {
|
||||
let msg = format!("autosave failed: {e}");
|
||||
if app.status.as_ref().is_none_or(|(s, _, _)| *s != msg) {
|
||||
app.set_status(msg, true);
|
||||
@@ -86,10 +23,10 @@ pub fn tick(app: &mut SolveApp) {
|
||||
|
||||
/// Start autosaving into `dir` and queue the designs that crashed apps left there.
|
||||
pub fn start(app: &mut SolveApp, dir: &std::path::Path, interval: std::time::Duration) {
|
||||
match Autosaver::new(dir, SHARED_CADENCE) {
|
||||
match Autosaver::new(dir, interval) {
|
||||
Ok(a) => {
|
||||
app.recoverable = recovery::orphans(dir);
|
||||
app.autosave = Some(Autosaves { dir: dir.to_path_buf(), interval, active: Some(a), last_at: Instant::now() });
|
||||
app.autosave = Some(a);
|
||||
}
|
||||
Err(e) => app.set_status(format!("autosave is off: {e}"), true),
|
||||
}
|
||||
@@ -97,17 +34,8 @@ pub fn start(app: &mut SolveApp, dir: &std::path::Path, interval: std::time::Dur
|
||||
|
||||
/// The app is closing: keep unsaved work for the next launch, drop everything else.
|
||||
pub fn close(app: &mut SolveApp) {
|
||||
if let Some(mut a) = app.autosave.take() {
|
||||
for slot in app.docs.background_mut() {
|
||||
let _ = save_slot(&a.dir, &mut slot.autosave, &slot.session, true, true);
|
||||
if let Some(saver) = slot.autosave.take() {
|
||||
saver.close(&slot.session);
|
||||
}
|
||||
}
|
||||
let _ = a.save(&app.session);
|
||||
if let Some(saver) = a.active.take() {
|
||||
saver.close(&app.session);
|
||||
}
|
||||
if let Some(a) = app.autosave.take() {
|
||||
a.close(&app.session);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -177,277 +105,8 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{Services, documents};
|
||||
use std::fs;
|
||||
|
||||
fn app(tag: &str, interval: Duration) -> (SolveApp, PathBuf) {
|
||||
let dir = std::env::temp_dir().join(format!("solidcraft-recovery-tabs-{tag}-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
let mut app = SolveApp::new(Session::default(), Services::default());
|
||||
start(&mut app, &dir, interval);
|
||||
(app, dir)
|
||||
}
|
||||
|
||||
fn edit(app: &mut SolveApp) {
|
||||
app.run("solid.box", json!({"length": 10, "width": 10, "height": 10})).unwrap();
|
||||
// Tests control the cadence without relying on how long the command took.
|
||||
app.big_operation = false;
|
||||
}
|
||||
|
||||
fn entries(dir: &Path) -> Vec<Entry> {
|
||||
let mut entries: Vec<Entry> = fs::read_dir(dir)
|
||||
.unwrap()
|
||||
.map(|p| p.unwrap().path())
|
||||
.filter(|p| p.extension().is_some_and(|e| e == "json"))
|
||||
.map(|p| serde_json::from_slice(&fs::read(p).unwrap()).unwrap())
|
||||
.collect();
|
||||
entries.sort_by(|a, b| a.name.cmp(&b.name));
|
||||
entries
|
||||
}
|
||||
|
||||
/// A tick, then wait for the writes it started on worker threads. Waiting writes nothing
|
||||
/// new: every design it would write was just written.
|
||||
fn tick_and_wait(app: &mut SolveApp) {
|
||||
tick(app);
|
||||
let Some(a) = app.autosave.as_mut() else { return };
|
||||
for slot in app.docs.background_mut() {
|
||||
if let Some(saver) = slot.autosave.as_mut() {
|
||||
let _ = saver.save(&slot.session);
|
||||
}
|
||||
}
|
||||
if let Some(saver) = a.active.as_mut() {
|
||||
let _ = saver.save(&app.session);
|
||||
}
|
||||
}
|
||||
|
||||
fn name(app: &mut SolveApp, name: &str) {
|
||||
app.run("file.new", json!({"name": name})).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dirty_background_tab_is_saved_and_offered_after_a_crash() {
|
||||
let (mut app, dir) = app("background", Duration::ZERO);
|
||||
name(&mut app, "Background A");
|
||||
edit(&mut app);
|
||||
let expected = app.session.doc.clone();
|
||||
documents::new_tab(&mut app);
|
||||
assert!(!app.session.is_dirty());
|
||||
tick_and_wait(&mut app);
|
||||
assert_eq!(entries(&dir).len(), 1);
|
||||
assert!(recovery::orphans(&dir).is_empty(), "all live entries stay locked");
|
||||
drop(app); // Simulate a crash: release locks without a final save.
|
||||
let restarted = restart(&dir);
|
||||
assert_eq!(restarted.recoverable.len(), 1);
|
||||
let entry = &restarted.recoverable[0];
|
||||
assert_eq!(entry.name, "Background A");
|
||||
assert_eq!(recovery::load(&dir, &entry.id).unwrap().0, *expected);
|
||||
drop(restarted);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
fn restart(dir: &Path) -> SolveApp {
|
||||
let mut app = SolveApp::new(Session::default(), Services::default());
|
||||
start(&mut app, dir, Duration::ZERO);
|
||||
app
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn switching_to_a_clean_tab_keeps_the_background_entry_and_its_id() {
|
||||
let (mut app, dir) = app("clean-tab", Duration::ZERO);
|
||||
edit(&mut app);
|
||||
tick_and_wait(&mut app);
|
||||
let before = entries(&dir);
|
||||
documents::new_tab(&mut app);
|
||||
tick_and_wait(&mut app);
|
||||
assert_eq!(entries(&dir), before, "the clean tab cannot delete another tab's entry");
|
||||
documents::switch(&mut app, 0);
|
||||
tick_and_wait(&mut app);
|
||||
assert_eq!(entries(&dir), before, "switching back preserves identity and skips unchanged content");
|
||||
drop(app);
|
||||
assert_eq!(recovery::orphans(&dir), before);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_dirty_tabs_keep_distinct_entries_and_recover_their_own_designs() {
|
||||
let (mut app, dir) = app("several", Duration::ZERO);
|
||||
let mut expected = Vec::new();
|
||||
for i in 0..3 {
|
||||
if i > 0 {
|
||||
documents::new_tab(&mut app);
|
||||
}
|
||||
name(&mut app, &format!("Design {i}"));
|
||||
for _ in 0..=i {
|
||||
edit(&mut app);
|
||||
}
|
||||
expected.push(app.session.doc.clone());
|
||||
}
|
||||
tick_and_wait(&mut app);
|
||||
let saved = entries(&dir);
|
||||
assert_eq!(saved.len(), 3);
|
||||
let ids: std::collections::HashSet<_> = saved.iter().map(|e| &e.id).collect();
|
||||
assert_eq!(ids.len(), 3);
|
||||
for i in [0, 2, 1, 0] {
|
||||
documents::switch(&mut app, i);
|
||||
tick_and_wait(&mut app);
|
||||
assert_eq!(entries(&dir), saved);
|
||||
}
|
||||
drop(app);
|
||||
let mut restarted = restart(&dir);
|
||||
assert_eq!(restarted.recoverable.len(), 3);
|
||||
for (entry, doc) in saved.iter().zip(expected) {
|
||||
assert_eq!(recovery::load(&dir, &entry.id).unwrap().0, *doc);
|
||||
restarted.run("doc.recover", json!({"dir": dir, "id": entry.id})).unwrap();
|
||||
assert_eq!(*restarted.session.doc, *doc);
|
||||
assert!(restarted.session.is_dirty());
|
||||
}
|
||||
drop(restarted);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saving_and_closing_remove_only_the_affected_tabs_entry() {
|
||||
let (mut app, dir) = app("cleanup", Duration::ZERO);
|
||||
for i in 0..3 {
|
||||
if i > 0 {
|
||||
documents::new_tab(&mut app);
|
||||
}
|
||||
name(&mut app, &format!("Design {i}"));
|
||||
edit(&mut app);
|
||||
}
|
||||
tick_and_wait(&mut app);
|
||||
let saved = entries(&dir);
|
||||
// Cleanup is immediate, even when the next autosave is far away.
|
||||
app.autosave.as_mut().unwrap().interval = Duration::from_secs(3600);
|
||||
app.run("file.save_as", json!({"path": dir.join("saved.solidcraft")})).unwrap();
|
||||
tick_and_wait(&mut app);
|
||||
assert_eq!(entries(&dir), saved[..2]);
|
||||
documents::close(&mut app, 0, false);
|
||||
documents::answer_prompt(&mut app, documents::Answer::Cancel);
|
||||
assert_eq!(entries(&dir), saved[..2], "cancelling close keeps recovery");
|
||||
documents::close(&mut app, 0, true); // Discard a background tab.
|
||||
assert_eq!(entries(&dir), saved[1..2]);
|
||||
documents::switch(&mut app, 0);
|
||||
documents::close(&mut app, 0, true); // Discard the active tab.
|
||||
assert!(entries(&dir).is_empty());
|
||||
edit(&mut app);
|
||||
app.autosave.as_mut().unwrap().save(&app.session).unwrap();
|
||||
assert_eq!(entries(&dir).len(), 1);
|
||||
documents::close(&mut app, 0, true); // Last tab becomes a fresh blank design.
|
||||
assert!(entries(&dir).is_empty());
|
||||
drop(app);
|
||||
assert!(recovery::orphans(&dir).is_empty());
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shutdown_keeps_all_unsaved_tabs_but_confirmed_quit_discards_them() {
|
||||
for discard in [false, true] {
|
||||
let (mut app, dir) = app(if discard { "quit" } else { "shutdown" }, Duration::from_secs(3600));
|
||||
edit(&mut app);
|
||||
documents::new_tab(&mut app);
|
||||
edit(&mut app);
|
||||
if discard {
|
||||
// Make entries first, then exercise Don't Save for every design.
|
||||
app.autosave.as_mut().unwrap().interval = Duration::ZERO;
|
||||
tick_and_wait(&mut app);
|
||||
assert_eq!(entries(&dir).len(), 2);
|
||||
documents::request_quit(&mut app);
|
||||
documents::answer_prompt(&mut app, documents::Answer::DontSave);
|
||||
documents::answer_prompt(&mut app, documents::Answer::DontSave);
|
||||
assert!(app.quit_requested);
|
||||
}
|
||||
close(&mut app);
|
||||
assert_eq!(recovery::orphans(&dir).len(), if discard { 0 } else { 2 });
|
||||
assert!(app.docs.background_mut().all(|s| s.autosave.is_none()), "shutdown releases every lock");
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cadence_and_big_operations_follow_the_document_and_preferences() {
|
||||
let (mut app, dir) = app("cadence", Duration::from_secs(3600));
|
||||
app.session.crash_journal = true;
|
||||
edit(&mut app);
|
||||
app.big_operation = true;
|
||||
documents::new_tab(&mut app);
|
||||
assert!(app.session.crash_journal);
|
||||
assert!(app.docs.background_mut().all(|s| !s.session.crash_journal));
|
||||
assert!(!app.big_operation);
|
||||
edit(&mut app);
|
||||
tick_and_wait(&mut app);
|
||||
assert_eq!(entries(&dir).len(), 1, "only the background big operation is due");
|
||||
assert!(app.docs.background_mut().all(|s| !s.big_operation));
|
||||
tick_and_wait(&mut app);
|
||||
assert_eq!(entries(&dir).len(), 1, "the ordinary active edit waits for the interval");
|
||||
app.autosave_minutes = 0.00001;
|
||||
crate::prefs::set_autosave(&mut app);
|
||||
app.autosave.as_mut().unwrap().last_at = Instant::now() - Duration::from_secs(1);
|
||||
tick_and_wait(&mut app);
|
||||
assert_eq!(entries(&dir).len(), 2, "changed preferences apply to every tab");
|
||||
drop(app);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_failed_autosave_does_not_skip_the_other_tabs() {
|
||||
let (mut app, dir) = app("failure", Duration::ZERO);
|
||||
name(&mut app, "A");
|
||||
edit(&mut app);
|
||||
tick_and_wait(&mut app);
|
||||
let id = entries(&dir)[0].id.clone();
|
||||
let blocked = dir.join(format!("{id}.solidcraft"));
|
||||
fs::remove_file(&blocked).unwrap();
|
||||
fs::create_dir(&blocked).unwrap();
|
||||
edit(&mut app);
|
||||
documents::new_tab(&mut app);
|
||||
name(&mut app, "B");
|
||||
edit(&mut app);
|
||||
// The writes run on worker threads: a failure is reported by a later tick.
|
||||
let failed = |app: &SolveApp| app.status.as_ref().is_some_and(|(message, _, error)| *error && message.contains("autosave failed"));
|
||||
let deadline = Instant::now() + Duration::from_secs(60);
|
||||
tick(&mut app);
|
||||
while !failed(&app) && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
tick(&mut app);
|
||||
}
|
||||
assert!(failed(&app));
|
||||
tick_and_wait(&mut app);
|
||||
let saved = entries(&dir);
|
||||
assert_eq!(saved.len(), 2);
|
||||
assert_eq!(recovery::load(&dir, &saved[1].id).unwrap().0, *app.session.doc);
|
||||
// Retrying at the next tick also recovers the previously failing tab.
|
||||
fs::remove_dir(&blocked).unwrap();
|
||||
tick_and_wait(&mut app);
|
||||
assert_eq!(recovery::load(&dir, &id).unwrap().0.features.len(), 2);
|
||||
drop(app);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tab_closed_while_its_autosave_is_written_leaves_nothing_to_recover() {
|
||||
let (mut app, dir) = app("discard-race", Duration::ZERO);
|
||||
name(&mut app, "Closed");
|
||||
// Enough of a design that its write is still running when the tab is closed.
|
||||
for i in 0..40 {
|
||||
app.run("solid.cylinder", json!({"radius": 3, "height": 5, "base": [i * 8, 0, 0], "operation": "new"})).unwrap();
|
||||
}
|
||||
app.big_operation = false;
|
||||
documents::new_tab(&mut app);
|
||||
tick(&mut app); // Starts writing the background tab on a worker thread.
|
||||
documents::close(&mut app, 0, true); // Don't Save, right away.
|
||||
let files = || fs::read_dir(&dir).unwrap().filter_map(|e| e.ok()).map(|e| e.file_name()).collect::<Vec<_>>();
|
||||
// A write that outlived the close would recreate the entry; give it time to.
|
||||
let deadline = Instant::now() + Duration::from_secs(2);
|
||||
while Instant::now() < deadline {
|
||||
assert!(entries(&dir).is_empty(), "the closed design came back: {:?}", files());
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
drop(app);
|
||||
assert!(recovery::orphans(&dir).is_empty());
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
use serde_json::json;
|
||||
use solidcraft_engine::recovery::Entry;
|
||||
|
||||
fn entry(id: &str, name: &str) -> Entry {
|
||||
Entry { id: id.into(), path: None, name: name.into(), saved_at: 0, features: 3 }
|
||||
|
||||
@@ -38,8 +38,6 @@ pub const POINTS: Accept = 512;
|
||||
pub const FEATURES: Accept = 1024;
|
||||
/// Points of the sketch being modified; unlike POINTS these never enable cross-sketch picking.
|
||||
pub const SKETCH_POINTS: Accept = 2048;
|
||||
/// The origin point, picked as a vertex of no body (in the viewport or the browser's Origin).
|
||||
pub const ORIGIN: Accept = 4096;
|
||||
|
||||
/// One selection input of a command dialog ("Profiles", "Edges", "Plane", ...).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -81,8 +79,7 @@ impl SelInput {
|
||||
Hit::SketchCurve { id, .. } if a & CURVES != 0 => Some(Sel::SketchCurve { id: id.clone() }),
|
||||
Hit::SketchPoint { id, .. } if a & SKETCH_POINTS != 0 => Some(Sel::SketchPoint { id: id.clone() }),
|
||||
Hit::SketchPoint { sketch, id, .. } if a & POINTS != 0 => Some(Sel::SketchPoint { id: format!("{sketch}:{id}") }),
|
||||
Hit::Vertex { body, point } if body.is_empty() && a & ORIGIN != 0 => Some(Sel::Vertex { body: String::new(), point: *point }),
|
||||
Hit::Vertex { body, point } if !body.is_empty() && a & VERTICES != 0 => Some(Sel::Vertex { body: body.clone(), point: *point }),
|
||||
Hit::Vertex { body, point } if a & VERTICES != 0 => Some(Sel::Vertex { body: body.clone(), point: *point }),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,24 +105,6 @@ pub fn score(q: &str, s: &str) -> u32 {
|
||||
300u32.saturating_sub(gaps * 20).max(10)
|
||||
}
|
||||
|
||||
/// Words people look for a command by that its name doesn't hold (file formats, what it is for).
|
||||
fn keywords(id: &str) -> &'static str {
|
||||
match id {
|
||||
"file.save_mesh" => "export stl 3mf mesh 3d print printing slicer",
|
||||
"file.export" => "export stl 3mf obj step urdf mesh 3d print",
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
|
||||
/// How well `q` matches a command's `keywords`: every word of the query starts a keyword.
|
||||
fn keyword_score(q: &str, keywords: &str) -> u32 {
|
||||
if keywords.is_empty() || q.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
let words = || keywords.split_whitespace();
|
||||
if q.split_whitespace().all(|w| words().any(|k| k.starts_with(w))) { 700 } else { 0 }
|
||||
}
|
||||
|
||||
/// A row of the box: the command id, its label, its icon, and where it lives on the toolbar
|
||||
/// (tab, panel; `None` off the toolbar), in the current language.
|
||||
pub type Row = (&'static str, &'static str, &'static str, Option<(&'static str, &'static str)>);
|
||||
@@ -136,7 +118,6 @@ pub fn search(app: &SolveApp, q: &str) -> Vec<Row> {
|
||||
let q = q.trim().to_lowercase();
|
||||
let mut v: Vec<(u32, Row)> = command_specs()
|
||||
.into_iter()
|
||||
.filter(|c| !crate::workspace::AGENT_ONLY.contains(&c.id))
|
||||
.filter_map(|c| {
|
||||
let (home_tab, home_panel) = crate::workspace::destination(c).unwrap_or(("", ""));
|
||||
let (label, tab, panel) = (crate::i18n::tr_label(c.label), crate::i18n::tr_label(home_tab), crate::i18n::tr_label(home_panel));
|
||||
@@ -144,7 +125,6 @@ pub fn search(app: &SolveApp, q: &str) -> Vec<Row> {
|
||||
let s = score(&q, label)
|
||||
.max(score(&q, c.label))
|
||||
.max(score(&q, c.id) * 9 / 10)
|
||||
.max(keyword_score(&q, keywords(c.id)))
|
||||
.max(score(&q, tab).max(score(&q, home_tab)) / 3)
|
||||
.max(score(&q, panel).max(score(&q, home_panel)) / 3);
|
||||
let recent = app.sbox.recent.iter().position(|r| r == c.id).map_or(0, |i| 2000u32.saturating_sub(i.min(2000) as u32));
|
||||
@@ -659,15 +639,6 @@ mod tests {
|
||||
assert_eq!((other.sbox.pinned.clone(), other.sbox.recent.len()), (vec!["solid.extrude".to_string()], 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn solve_sketch_is_not_offered_but_the_command_remains() {
|
||||
let app = SolveApp::new(solidcraft_engine::Session::default(), Default::default());
|
||||
for q in ["solve", "sketch.solve", ""] {
|
||||
assert!(!search(&app, q).iter().any(|x| x.0 == "sketch.solve"), "{q:?}");
|
||||
}
|
||||
assert!(solidcraft_engine::find_command("sketch.solve").is_some(), "agents and MCP keep it");
|
||||
}
|
||||
|
||||
/// The box shows each command's label and place in the current language, and finds a name
|
||||
/// typed in that language, in English, or an id (#2544).
|
||||
#[test]
|
||||
|
||||
@@ -649,33 +649,3 @@ fn trim_hover_shows_the_piece_a_click_takes_away() {
|
||||
h.step(&json!({"move":{"world":[15,0,0]}})).unwrap();
|
||||
assert!(trim_hover_piece(&h.app, sid, &line).is_none(), "only Trim shows a piece");
|
||||
}
|
||||
|
||||
/// #3141: the 2-tangent circle tool, clicked on two sides of a rectangle drawn away from the
|
||||
/// origin, puts its circle in the corner between the clicks without moving the rectangle, and
|
||||
/// fixed sides no longer make it fail.
|
||||
#[test]
|
||||
fn two_tangent_circle_clicked_on_two_sides_fits_the_corner_and_moves_nothing() {
|
||||
for fixed in [false, true] {
|
||||
let mut h = crate::scenario::Harness::new();
|
||||
h.app.run("sketch.create", json!({"plane":"XY"})).unwrap();
|
||||
let r = h.app.run("sketch.rectangle.two_point", json!({"p0":[-800,0],"p1":[-300,500]})).unwrap();
|
||||
if fixed {
|
||||
h.app.run("sketch.constraint.fix", json!({"entities": r["curves"]})).unwrap();
|
||||
}
|
||||
h.step(&json!({"call":"ui.view","params":{"view":"fit"}})).unwrap();
|
||||
h.settle();
|
||||
let sid = h.app.session.active_sketch.unwrap();
|
||||
let points =
|
||||
|h: &crate::scenario::Harness| h.app.session.model.state().sketch(sid).unwrap().sketch.points.iter().map(|p| p.pos).collect::<Vec<_>>();
|
||||
let before = points(&h);
|
||||
h.step(&json!({"start":"sketch.circle.two_tangent"})).unwrap();
|
||||
h.step(&json!({"click":{"world":[-550,0,0]}})).unwrap();
|
||||
h.step(&json!({"click":{"world":[-800,250,0]}})).unwrap();
|
||||
let sk = h.app.session.model.state().sketch(sid).unwrap().sketch.clone();
|
||||
let circle = sk.curves.iter().position(|c| matches!(c.kind, CurveKind::Circle { .. }));
|
||||
let circle = circle.unwrap_or_else(|| panic!("fixed {fixed}: no circle: {:?}", h.app.status));
|
||||
assert!(sk.center(circle).unwrap().dist(Vec2::new(-750.0, 50.0)) < 1e-6, "fixed {fixed}: {:?}", sk.center(circle));
|
||||
let after = points(&h);
|
||||
assert!(before.iter().zip(&after).all(|(a, b)| a.dist(*b) < 1e-9), "fixed {fixed}: the rectangle moved: {after:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! buttons. Options: the line type of the selected curves (normal, construction, centerline),
|
||||
//! Look At, and the display toggles kept with the sketch (grid, snap, slice, profiles, points,
|
||||
//! dimensions, constraints, projected geometry, construction geometry, 3D sketch); the sketch's
|
||||
//! degrees of freedom. Finish Sketch sits at the bottom, beside the ribbon's Exit group. Toggles run `sketch.options`, line types
|
||||
//! degrees of freedom. Finish Sketch lives in the ribbon Exit group. Toggles run `sketch.options`, line types
|
||||
//! `sketch.construction` / `sketch.centerline`.
|
||||
//!
|
||||
//! The line type is also a drawing mode: with nothing selected, Construction (or X) makes what
|
||||
@@ -43,18 +43,6 @@ pub fn has_geometry(sketch: &solidcraft_engine::sketch::Sketch) -> bool {
|
||||
!sketch.curves.is_empty() || !sketch.wires.is_empty()
|
||||
}
|
||||
|
||||
/// Nothing the user added: no curve, 3D curve, constraint or dimension, pattern, projection,
|
||||
/// text or offset, and no point but the fixed origin.
|
||||
pub fn is_blank(sketch: &solidcraft_engine::sketch::Sketch) -> bool {
|
||||
!has_geometry(sketch)
|
||||
&& sketch.constraints.is_empty()
|
||||
&& sketch.patterns.is_empty()
|
||||
&& sketch.links.is_empty()
|
||||
&& sketch.offsets.is_empty()
|
||||
&& sketch.freeform_offsets.is_empty()
|
||||
&& sketch.points.iter().all(|p| p.id == "origin")
|
||||
}
|
||||
|
||||
/// The degrees-of-freedom line: "No geometry yet" (an empty sketch only has its fixed origin),
|
||||
/// "Fully constrained" or "N degrees of freedom".
|
||||
pub fn dof_text(dof: usize, ok: bool, has_geometry: bool) -> String {
|
||||
@@ -355,7 +343,6 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
let mut linetype = None;
|
||||
let mut construction = false;
|
||||
let mut look = false;
|
||||
let mut finish = false;
|
||||
let mut tie = false;
|
||||
let mut start = None;
|
||||
let feature = active_feature(app);
|
||||
@@ -473,10 +460,6 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
section_alias("sketch_palette:options_fold", "ui.palette_more");
|
||||
}
|
||||
crate::ui_kit::Part::Footer => {
|
||||
let button = crate::ui_kit::wide_primary_button(ui, "Finish Sketch");
|
||||
crate::scenario::publish_rect("sketch_palette:finish", button.rect);
|
||||
crate::scenario::publish_handle("sketch_palette:finish", button.rect.center());
|
||||
finish = button.clicked();
|
||||
let (at, slice) = crate::ui_kit::button_pair(
|
||||
ui,
|
||||
"sketch_palette",
|
||||
@@ -497,6 +480,13 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
if let Some(rect) = app.viewport.palette_rect {
|
||||
crate::scenario::publish_rect("sketch_palette:outer", rect);
|
||||
}
|
||||
// Compatibility automation hook now points at the single Finish action in the ribbon.
|
||||
if let Some(at) = crate::scenario::handle_at("button:sketch.finish") {
|
||||
crate::scenario::publish_handle("sketch_palette:finish", at);
|
||||
if let Some(rect) = crate::scenario::rect_of("button:sketch.finish") {
|
||||
crate::scenario::publish_rect("sketch_palette:finish", rect);
|
||||
}
|
||||
}
|
||||
if let Some((key, on)) = set {
|
||||
let mut params = serde_json::Map::new();
|
||||
params.insert(key, Value::Bool(on));
|
||||
@@ -523,9 +513,6 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
if look {
|
||||
crate::dialogs::look_at_sketch_again(app);
|
||||
}
|
||||
if finish {
|
||||
app.finish_sketch();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -603,18 +590,6 @@ mod tests {
|
||||
assert!(h.app.session.active_sketch.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn palette_has_a_finish_sketch_button_that_finishes_the_sketch() {
|
||||
let mut h = crate::scenario::Harness::new();
|
||||
h.app.run("sketch.create", json!({"plane":"XY"})).unwrap();
|
||||
h.settle();
|
||||
let at = crate::scenario::handle_at("sketch_palette:finish").expect("the palette ends in Finish Sketch");
|
||||
assert!(crate::scenario::rect_of("sketch_palette:look_at").is_some(), "Look At | Slice stay");
|
||||
assert!(crate::scenario::handle_at("button:sketch.finish").is_some(), "and so does the ribbon's Finish");
|
||||
h.call("ui.click", json!({"x":at.x,"y":at.y}));
|
||||
assert!(h.app.session.active_sketch.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn construction_shortcut_keeps_the_drawing_tool_and_commits_its_line_type() {
|
||||
for command in ["sketch.line", "sketch.rectangle.two_point", "sketch.circle.center"] {
|
||||
@@ -963,84 +938,4 @@ mod tests {
|
||||
h.settle();
|
||||
assert_ne!(line(&h), "No geometry yet", "a drawn rectangle is geometry");
|
||||
}
|
||||
|
||||
/// One Esc cancels the tool and keeps the sketch open; two quick presses finish it (the
|
||||
/// sketch is kept and listed in the timeline), also when the first press cancelled a tool.
|
||||
#[test]
|
||||
fn escape_cancels_then_a_quick_second_escape_finishes_the_sketch() {
|
||||
let apart = |h: &mut crate::scenario::Harness| h.frames(60);
|
||||
let mut h = crate::scenario::Harness::new();
|
||||
h.app.run("sketch.create", json!({"plane":"XY"})).unwrap();
|
||||
h.app.run("sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[40,30]})).unwrap();
|
||||
h.settle();
|
||||
h.step(&json!({"start":"sketch.line"})).unwrap();
|
||||
assert!(h.app.tool.is_some());
|
||||
h.step(&json!({"key":"Escape"})).unwrap();
|
||||
assert!(h.app.tool.is_none(), "one Esc puts the tool down");
|
||||
apart(&mut h);
|
||||
h.step(&json!({"key":"Escape"})).unwrap();
|
||||
apart(&mut h);
|
||||
assert!(h.app.session.active_sketch.is_some(), "single presses keep the sketch open");
|
||||
|
||||
// A quick double press finishes and keeps the sketch.
|
||||
h.step(&json!({"key":"Escape"})).unwrap();
|
||||
h.step(&json!({"key":"Escape"})).unwrap();
|
||||
h.settle();
|
||||
assert!(h.app.session.active_sketch.is_none(), "a double Esc finishes the sketch");
|
||||
assert_eq!(h.app.ui.tab, "MODEL");
|
||||
assert!(crate::scenario::handle_at("timeline:Sketch1").is_some(), "the sketch is kept");
|
||||
let sketch = h.app.session.execute("sketch.inspect", &json!({"sketch": 1})).unwrap();
|
||||
assert_eq!(sketch["curves"].as_array().map(Vec::len), Some(4), "{sketch}");
|
||||
|
||||
// With a tool active: the first press cancels it, the second finishes.
|
||||
h.step(&json!({"click": {"handle": "timeline:Sketch1"}, "double": true})).unwrap();
|
||||
h.settle();
|
||||
assert!(h.app.session.active_sketch.is_some());
|
||||
apart(&mut h);
|
||||
h.step(&json!({"start":"sketch.circle.center"})).unwrap();
|
||||
assert!(h.app.tool.is_some());
|
||||
h.step(&json!({"key":"Escape"})).unwrap();
|
||||
h.step(&json!({"key":"Escape"})).unwrap();
|
||||
h.settle();
|
||||
assert!(h.app.tool.is_none() && h.app.session.active_sketch.is_none());
|
||||
assert!(crate::scenario::handle_at("timeline:Sketch1").is_some());
|
||||
// Outside a sketch a double Esc only clears, as before.
|
||||
h.step(&json!({"key":"Escape"})).unwrap();
|
||||
h.step(&json!({"key":"Escape"})).unwrap();
|
||||
assert!(h.app.session.active_sketch.is_none());
|
||||
}
|
||||
|
||||
/// A double Esc on a sketch left blank takes it away (no empty sketch in the browser or the
|
||||
/// timeline, one undo step) and puts the view back; one line is enough to keep it.
|
||||
#[test]
|
||||
fn a_quick_double_escape_discards_a_blank_sketch_and_keeps_one_with_a_line() {
|
||||
let mut h = crate::scenario::Harness::new();
|
||||
h.call("ui.view", json!({"view": "iso"}));
|
||||
h.frames(3);
|
||||
let undo = h.app.session.undo.len();
|
||||
h.step(&json!({"start":"sketch.create"})).unwrap();
|
||||
h.step(&json!({"click": {"plane": "XY"}})).unwrap();
|
||||
h.settle();
|
||||
assert!(h.app.session.active_sketch.is_some());
|
||||
h.step(&json!({"key":"Escape"})).unwrap();
|
||||
h.step(&json!({"key":"Escape"})).unwrap();
|
||||
h.settle();
|
||||
crate::scenario::check(&mut h, &json!({"sketching": false, "camera": {"yaw_deg": -45, "pitch_deg": 35}})).unwrap();
|
||||
assert_eq!(h.app.ui.tab, "MODEL");
|
||||
assert!(h.app.session.doc.features.is_empty(), "the blank sketch is gone");
|
||||
assert!(crate::scenario::handles("timeline:").iter().all(|(n, _)| !n.contains("Sketch")));
|
||||
assert!(crate::scenario::handle_at("row:Sketch1").is_none());
|
||||
assert!(h.app.session.undo.len() <= undo + 2, "creating and discarding are at most two steps");
|
||||
|
||||
h.step(&json!({"start":"sketch.create"})).unwrap();
|
||||
h.step(&json!({"click": {"plane": "XY"}})).unwrap();
|
||||
h.app.run("sketch.line", json!({"points": [[0, 0], [30, 10]]})).unwrap();
|
||||
h.settle();
|
||||
h.step(&json!({"key":"Escape"})).unwrap();
|
||||
h.step(&json!({"key":"Escape"})).unwrap();
|
||||
h.settle();
|
||||
assert!(h.app.session.active_sketch.is_none());
|
||||
assert_eq!(h.app.session.doc.features.len(), 1, "a sketch with a line is kept");
|
||||
assert!(crate::scenario::handles("timeline:").iter().any(|(n, _)| n.contains("Sketch")));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,12 +67,9 @@ fn a_sketch_key_with_nothing_selected_asks_for_the_plane_then_starts_the_tool()
|
||||
assert!(h.app.dialog.is_none());
|
||||
}
|
||||
|
||||
/// #1804: Escape puts down the sketch tool. Another Escape, on its own, does not leave the
|
||||
/// sketch; only a quick second press does (and finishes it, keeping it).
|
||||
/// #1804: Escape puts down the sketch tool. Another Escape does not leave the sketch.
|
||||
#[test]
|
||||
fn a_second_escape_stays_in_the_sketch() {
|
||||
// Presses further apart than the double-press window.
|
||||
let pause = |h: &mut Harness| h.frames((crate::toolbar::ESCAPE_TWICE_S * 60.0) as usize + 6);
|
||||
let mut h = Harness::new();
|
||||
h.app.run("sketch.create", json!({"plane":"XY"})).unwrap();
|
||||
let sketch = h.app.session.active_sketch;
|
||||
@@ -82,21 +79,15 @@ fn a_second_escape_stays_in_the_sketch() {
|
||||
press(&mut h, "Escape");
|
||||
assert!(tool(&h).is_none(), "the first Escape puts the tool down");
|
||||
assert_eq!(h.app.session.active_sketch, sketch);
|
||||
pause(&mut h);
|
||||
press(&mut h, "Escape");
|
||||
assert_eq!(h.app.session.active_sketch, sketch, "a second Escape stays in the sketch");
|
||||
h.app.run("sketch.line", json!({"points":[[0,0],[10,0]]})).unwrap();
|
||||
h.app.session.selection = vec![Sel::SketchCurve { id: "l1".into() }];
|
||||
pause(&mut h);
|
||||
press(&mut h, "Escape");
|
||||
assert!(h.app.session.selection.is_empty(), "Escape still clears a selection");
|
||||
assert_eq!(h.app.session.active_sketch, sketch);
|
||||
pause(&mut h);
|
||||
press(&mut h, "Escape");
|
||||
assert_eq!(h.app.session.active_sketch, sketch, "Escape after clearing the selection stays in the sketch");
|
||||
press(&mut h, "Escape");
|
||||
assert!(h.app.session.active_sketch.is_none(), "a quick second Escape finishes the sketch");
|
||||
assert_eq!(h.app.session.doc.features.len(), 1, "and keeps it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -595,7 +595,7 @@ pub fn hint(id: &str) -> Option<String> {
|
||||
"sketch.edit_text" => "Edit Text: click a letter interior or outline",
|
||||
"sketch.blend_curve" => "Blend curve: click the ends of two curves",
|
||||
"sketch.constraint.curvature" => "Curvature: click two curves that share an end",
|
||||
"sketch.circle.two_tangent" => "2-tangent circle: click two curves (the circle goes between the two clicks)",
|
||||
"sketch.circle.two_tangent" => "2-tangent circle: click two curves (the circle goes near the second click)",
|
||||
"sketch.circle.three_tangent" => "3-tangent circle: click three curves",
|
||||
"sketch.constrainer" => "Constrain: click one or two entities; right-click to apply",
|
||||
"sketch.constraint.polygon" => "Polygon: click the lines of a closed chain; right-click to apply",
|
||||
@@ -1007,9 +1007,7 @@ fn run_entities(app: &mut SolveApp, t: &Tool) {
|
||||
"sketch.constraint.curvature" => json!({"a": k[0], "b": k[1]}),
|
||||
"sketch.circle.two_tangent" => {
|
||||
let r = round_nice(curve_len(app, &k[0]).min(curve_len(app, &k[1])) * 0.1);
|
||||
// Between the two clicks: each lies on its curve, so the circle in the corner they
|
||||
// span is the one nearest their midpoint (#3141).
|
||||
let near = xy(t.pts.iter().fold(Vec2::ZERO, |a, p| a + p.0) / t.pts.len().max(1) as f64);
|
||||
let near = t.pts.last().map(|p| xy(p.0)).unwrap_or(json!([0, 0]));
|
||||
json!({"curves": k, "radius": r, "near": near})
|
||||
}
|
||||
"sketch.circle.three_tangent" => {
|
||||
|
||||
@@ -503,7 +503,7 @@ fn file_menu(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
}
|
||||
crate::ui_kit::Menu::button(ui, app.tr("ui.open_recent"), |ui| {
|
||||
for path in app.home.recent.clone() {
|
||||
let missing = !crate::home::available(app, &path);
|
||||
let missing = !solidcraft_engine::io::vfs::exists(&path);
|
||||
let label = format!("{path}{}", if missing { " (missing)" } else { "" });
|
||||
if crate::context_menu::button(ui, &label, "open").clicked() {
|
||||
crate::home::open_recent(app, &path);
|
||||
@@ -555,12 +555,8 @@ fn file_menu(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
close = true;
|
||||
}
|
||||
ui.separator();
|
||||
if item_if(ui, "Export STL…", "", "mesh_export", shown) {
|
||||
crate::dialogs_save_mesh::start_with_format(app, "stl");
|
||||
close = true;
|
||||
}
|
||||
if item_if(ui, "Export 3MF…", "", "mesh_export", shown) {
|
||||
crate::dialogs_save_mesh::start_with_format(app, "3mf");
|
||||
if item_if(ui, "Save as mesh…", "", "mesh_export", shown) {
|
||||
app.start("file.save_mesh");
|
||||
close = true;
|
||||
}
|
||||
if item_if(ui, "Export STEP…", "", "export", shown) {
|
||||
@@ -775,12 +771,6 @@ fn ribbon_text(ui: &egui::Ui, at: egui::Pos2, text: &str, size: f32, color: Colo
|
||||
ui.painter().galley(origin, galley, color);
|
||||
}
|
||||
|
||||
/// SKETCH while editing a sketch and SHEET METAL while a sheet body is active take the contextual
|
||||
/// tab style; SHEET METAL is an ordinary tab otherwise.
|
||||
fn contextual_tab(app: &SolveApp, tab: &str) -> bool {
|
||||
tab == "SKETCH" || (tab == "SHEET METAL" && crate::workspace::sheet_body(app).is_some())
|
||||
}
|
||||
|
||||
fn ribbon_tabs(app: &mut SolveApp, ui: &mut egui::Ui, row: Rect) {
|
||||
let t = Tokens::get();
|
||||
let tabs = crate::workspace::visible_tabs(app);
|
||||
@@ -793,7 +783,7 @@ fn ribbon_tabs(app: &mut SolveApp, ui: &mut egui::Ui, row: Rect) {
|
||||
.collect();
|
||||
let tabs_width: f32 = widths.iter().sum::<f32>()
|
||||
+ tabs.len().saturating_sub(1) as f32 * 2.0
|
||||
+ tabs.iter().filter(|tab| contextual_tab(app, tab)).count() as f32 * 6.0;
|
||||
+ tabs.iter().filter(|tab| matches!(**tab, "SKETCH" | "SHEET METAL")).count() as f32 * 6.0;
|
||||
let search_width = crate::ui_kit::CommandSearch::closed_width(ui.ctx());
|
||||
// The first tab and the search field sit the same distance from the card's top, left and right
|
||||
// edges, so their outer corners are concentric with the card's corners.
|
||||
@@ -823,7 +813,7 @@ fn ribbon_tabs(app: &mut SolveApp, ui: &mut egui::Ui, row: Rect) {
|
||||
let (all, _) = ui.allocate_exact_size(vec2(tabs_width, TAB_ROW_HEIGHT), Sense::hover());
|
||||
let mut x = all.left();
|
||||
for (tab, width) in tabs.into_iter().zip(widths) {
|
||||
let contextual = contextual_tab(app, tab);
|
||||
let contextual = matches!(tab, "SKETCH" | "SHEET METAL");
|
||||
if contextual {
|
||||
x += 6.0;
|
||||
}
|
||||
@@ -1005,13 +995,11 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
})
|
||||
.collect();
|
||||
let right = r.right();
|
||||
// The Sketch exit group follows the last sketch panel, and is always kept room for so it
|
||||
// stays reachable at every width; when panels go into the » menu it moves to the far right.
|
||||
// Keep the Sketch exit group at the far right and reachable at every width.
|
||||
let finish_plan = sizes.last().filter(|_| tab == "SKETCH").map(Plan::full);
|
||||
let finish_width = finish_plan.as_ref().map_or(0.0, |p| p.width().max(80.0));
|
||||
let normal_count = sizes.len().saturating_sub(usize::from(finish_plan.is_some()));
|
||||
let mut plans = fit(sizes.get(..normal_count).unwrap_or_default(), right - 4.0 - px - finish_width);
|
||||
let finish_right = plans.iter().any(|p| p.fit == Fit::More);
|
||||
plans.extend(finish_plan);
|
||||
crate::scenario::publish_count("toolbar_collapsed", plans.iter().filter(|p| p.fit == Fit::Collapsed).count() as f64);
|
||||
crate::scenario::publish_count("toolbar_more", plans.iter().filter(|p| p.fit == Fit::More).count() as f64);
|
||||
@@ -1029,7 +1017,7 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
let trimmed = plan.shown < plan.widths.len();
|
||||
let finish = tab == "SKETCH" && *panel == "FINISH SKETCH";
|
||||
let width = if finish { finish_width } else { plan.width() };
|
||||
if finish && finish_right {
|
||||
if finish {
|
||||
px = right - finish_width;
|
||||
painter.line_segment([pos2(px, top), pos2(px, r.bottom() - 1.0)], Stroke::new(1.0, t.border));
|
||||
}
|
||||
@@ -1531,10 +1519,6 @@ fn ribbon_tooltip(app: &SolveApp, response: egui::Response, command: &solidcraft
|
||||
if let Some(description) = description {
|
||||
ui.add(egui::Label::new(description).wrap());
|
||||
}
|
||||
// The tool's own help, when it has one (#2758).
|
||||
if let Some(help) = crate::command_help::help(command.id) {
|
||||
ui.add(egui::Label::new(egui::RichText::new(help).color(t.text_dim)).wrap());
|
||||
}
|
||||
if let Some(reason) = disabled {
|
||||
ui.add(egui::Label::new(egui::RichText::new(reason).color(t.text_dim)).wrap());
|
||||
}
|
||||
@@ -1636,11 +1620,9 @@ fn dropdown_row(app: &SolveApp, ui: &mut egui::Ui, c: &'static solidcraft_engine
|
||||
if pin.on_hover_text(tip).clicked() {
|
||||
return RowAction::TogglePin;
|
||||
}
|
||||
// A disabled row says why; a documented command also shows its help (#2758).
|
||||
let reason = info.disabled_reason.as_deref().filter(|_| !info.enabled);
|
||||
let resp = match crate::command_help::row_tip(c.id, &label, c.shortcut, reason) {
|
||||
Some(tip) => crate::command_help::tooltip(resp, c.id, tip),
|
||||
None => resp,
|
||||
let resp = match &info.disabled_reason {
|
||||
Some(why) if !info.enabled => resp.on_hover_text(why),
|
||||
_ => resp,
|
||||
};
|
||||
if resp.secondary_clicked() {
|
||||
return RowAction::Menu(resp.interact_pointer_pos().unwrap_or(rect.left_bottom()));
|
||||
@@ -1785,9 +1767,6 @@ pub(crate) fn selection_filter(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Two Esc presses within this many seconds finish the open sketch.
|
||||
pub const ESCAPE_TWICE_S: f64 = 0.4;
|
||||
|
||||
/// Global keyboard shortcuts (when no text field has focus).
|
||||
pub fn shortcuts(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
if app.file_load.busy() {
|
||||
@@ -1816,10 +1795,6 @@ pub fn shortcuts(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
}
|
||||
for k in keys {
|
||||
use egui::Key;
|
||||
// Only Esc pressed twice in a row finishes a sketch: any other key in between resets it.
|
||||
if k != Key::Escape {
|
||||
app.last_escape = None;
|
||||
}
|
||||
if shown && crate::navigation::view_key(app, ctx, k, mods) {
|
||||
continue;
|
||||
}
|
||||
@@ -1850,29 +1825,6 @@ pub fn shortcuts(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
match k {
|
||||
Key::Escape => {
|
||||
app.esc_handled = true;
|
||||
// Two quick presses in a sketch finish it (keeping it, like Finish Sketch);
|
||||
// the first one has already cancelled whatever was active.
|
||||
let now = ctx.input(|i| i.time);
|
||||
let again = app.last_escape.is_some_and(|t| now - t <= ESCAPE_TWICE_S);
|
||||
app.last_escape = Some(now);
|
||||
// Not while a tool is still out (its first Esc only ended a chain): this press
|
||||
// puts it down, and the next quick one finishes.
|
||||
if again
|
||||
&& app.tool.is_none()
|
||||
&& app.dialog.is_none()
|
||||
&& let Some(sketch) = app.session.active_sketch
|
||||
{
|
||||
app.last_escape = None;
|
||||
// A sketch left blank is taken away instead, in one undo step, so no empty
|
||||
// sketch stays behind.
|
||||
let blank = app.session.doc.sketch(sketch).is_ok_and(crate::sketch_palette::is_blank);
|
||||
let depth = app.session.undo.len();
|
||||
app.finish_sketch();
|
||||
if blank && app.session.active_sketch.is_none() && app.run("timeline.delete", json!({ "feature": sketch.to_string() })).is_ok() {
|
||||
app.session.undo.truncate(depth + 1);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if crate::sketch_text_move::cancel_drag(app) {
|
||||
continue;
|
||||
}
|
||||
@@ -1886,8 +1838,8 @@ pub fn shortcuts(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
app.tree.picked_joints.clear();
|
||||
let _ = app.run("select.clear", json!({}));
|
||||
}
|
||||
// A single Esc with nothing left to cancel keeps the sketch open (#1804); a quick
|
||||
// second press finishes it (above).
|
||||
// An open sketch with nothing left to cancel stays open (#1804). Finish Sketch
|
||||
// is what leaves it, so a second Escape after putting a tool down is harmless.
|
||||
}
|
||||
Key::S if !mods.shift && !mods.alt => {
|
||||
app.start("ui.palette");
|
||||
@@ -1941,27 +1893,6 @@ mod header_report_tests {
|
||||
assert!(!solidcraft_engine::io::is_design_container(&std::fs::read(saved).unwrap()), "subsequent Save keeps a .json choice");
|
||||
}
|
||||
|
||||
/// File › Export STL… and Export 3MF… both open the Save as mesh dialog with their format
|
||||
/// chosen (whatever was used last), and command search finds the export by format or purpose.
|
||||
#[test]
|
||||
fn file_menu_has_export_stl_and_3mf_that_open_the_mesh_dialog_with_that_format() {
|
||||
let mut h = crate::scenario::Harness::new();
|
||||
h.app.run("solid.box", json!({"length":2,"width":3,"height":4})).unwrap();
|
||||
h.app.preferences.save_mesh_format = "3mf".into();
|
||||
for (item, format) in [("Export STL…", "stl"), ("Export 3MF…", "3mf")] {
|
||||
h.frames(3);
|
||||
h.step(&json!({"click":{"handle":"appbar:file"}})).unwrap();
|
||||
h.step(&json!({"widget": item})).unwrap();
|
||||
let Some(crate::dialogs::Kind::SaveMesh(k)) = h.app.dialog.as_ref().map(|d| &d.kind) else { panic!("{item}: no Save as mesh dialog") };
|
||||
assert_eq!(k.format_name(), format, "{item}");
|
||||
crate::dialogs::cancel(&mut h.app);
|
||||
}
|
||||
for q in ["3mf", "stl", "export 3mf", "print"] {
|
||||
let found = crate::shortcut_box::search(&h.app, q);
|
||||
assert!(found.iter().any(|r| r.0 == "file.save_mesh"), "{q}: {:?}", found.iter().map(|r| r.0).collect::<Vec<_>>());
|
||||
}
|
||||
}
|
||||
|
||||
/// The browser build's File > Download design hands the open design to the host as a
|
||||
/// `.solidcraft` container named after it; a host that saves real files shows no such item.
|
||||
#[test]
|
||||
@@ -2413,7 +2344,7 @@ mod home_tests {
|
||||
fn needs_design_tooltip_is_translated() {
|
||||
let english = crate::i18n::Locale::for_language("en").text("ui.needs_design");
|
||||
assert!(english.contains("{command}"));
|
||||
for catalog in crate::i18n::LOCALES.iter().filter(|c| !matches!(c.id, "en" | "en-GB")) {
|
||||
for catalog in crate::i18n::LOCALES.iter().filter(|c| c.id != "en") {
|
||||
let text = crate::i18n::Locale::for_language(catalog.id).text("ui.needs_design");
|
||||
assert!(text != english && text.contains("{command}"), "{} must translate ui.needs_design", catalog.id);
|
||||
}
|
||||
@@ -2776,8 +2707,7 @@ mod fill_width_tests {
|
||||
let at = format!("{tab} at {w}");
|
||||
let bar = crate::scenario::rect_of("toolbar").unwrap();
|
||||
let finish = crate::scenario::rect_of("panel:SKETCH:FINISH SKETCH");
|
||||
// The room for the other panels: the bar less the Finish group kept for it.
|
||||
let right = bar.right() - 4.0 - finish.map_or(0.0, |f| f.width() + 4.0);
|
||||
let right = finish.map_or(bar.right() - 4.0, |f| f.left() - 4.0);
|
||||
let count = |name: &str| crate::scenario::count_of(name).unwrap_or(-1.0);
|
||||
let (collapsed, trimmed, more) = (count("toolbar_collapsed"), count("toolbar_trimmed"), count("toolbar_more"));
|
||||
let lists = crate::toolbar_custom::panel_lists(tab);
|
||||
@@ -2824,11 +2754,7 @@ mod fill_width_tests {
|
||||
}
|
||||
if sketch {
|
||||
let finish = finish.expect("Finish group stays visible");
|
||||
if more > 0.0 {
|
||||
assert_eq!(finish.right(), bar.right(), "{at}: Finish moves right of the » menu");
|
||||
} else {
|
||||
assert!((finish.left() - end).abs() < 0.5, "{at}: Finish follows the last panel ({} vs {end})", finish.left());
|
||||
}
|
||||
assert_eq!(finish.right(), bar.right(), "{at}: Finish stays anchored right");
|
||||
assert!(crate::scenario::handle_at("button:sketch.finish").is_some(), "{at}: Finish stays reachable");
|
||||
}
|
||||
// The assistant lives in the title bar; visible ribbon tabs fit before search.
|
||||
|
||||
@@ -279,17 +279,6 @@ pub(crate) fn primary_button(ui: &mut Ui, label: &str) -> Response {
|
||||
response
|
||||
}
|
||||
|
||||
/// Accent action across the full width of its container, for the bottom of a panel. Tokens:
|
||||
/// `form_primary, on_accent, form_button_height, font_label`.
|
||||
pub(crate) fn wide_primary_button(ui: &mut Ui, label: &str) -> Response {
|
||||
let t = Tokens::get();
|
||||
let text = RichText::new(crate::i18n::tr_label(label)).size(t.font_label).color(t.on_accent);
|
||||
let size = vec2(ui.available_width(), t.form_button_height);
|
||||
let response = ui.add(egui::Button::new(crate::fonts::RichTextExt::bold_face(text)).fill(t.form_primary).min_size(size));
|
||||
pointer_on_hover(ui, &response);
|
||||
response
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "actions_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
@@ -609,9 +609,6 @@ const ELEMENTS: &[Element] = &[
|
||||
primary_button(ui, "Create");
|
||||
});
|
||||
}),
|
||||
element!("wide_primary_button", |ui, _| {
|
||||
wide_primary_button(ui, "Finish Sketch");
|
||||
}),
|
||||
element!("button", "dialog:row:Gallery", Some("dialog:button:Gallery:Add"), |ui, _| {
|
||||
row(ui, "Gallery", |ui| {
|
||||
button(ui, "Add", Button::Normal);
|
||||
|
||||
+187
-46
@@ -1172,7 +1172,6 @@ pub(crate) fn pick_cached(app: &mut SolveApp, proj: &Proj, pos: Pos2) -> Vec<Hit
|
||||
app.dialog.as_ref().and_then(|d| d.active_input()).map(|i| i.accept).hash(&mut h);
|
||||
app.session.visibility.hidden_bodies.hash(&mut h);
|
||||
app.session.visibility.hidden_occurrences.hash(&mut h);
|
||||
origin_point_shown(app).hash(&mut h);
|
||||
app.perspective_view().hash(&mut h);
|
||||
(proj.rect.width().to_bits(), proj.rect.height().to_bits()).hash(&mut h);
|
||||
crate::sketch_display::projection_key(proj, app.viewport.pixels_per_point()).hash(&mut h);
|
||||
@@ -1366,12 +1365,41 @@ fn pick_hits(app: &SolveApp, proj: &Proj, pos: Pos2, other_sketch_points: bool,
|
||||
// The edges seen near the cursor, when the GPU pick buffer has them for this view (Select
|
||||
// Other wants hidden ones too).
|
||||
let seen = if all { None } else { crate::pick_buffer::edges_near(app, proj, pos, &st) };
|
||||
// The face under the pointer wins over the vertices and edges inside it when they are not
|
||||
// the boundary the pointer means: the edges between faces picked as one with it (a modelled
|
||||
// thread's thousands of faces), and, when the face is small on screen (a finely faceted
|
||||
// surface), any vertex or edge further than a couple of points away.
|
||||
let inside = match bestf.as_ref().map(|(_, h)| h) {
|
||||
Some(Hit::Face { body, index, .. }) if !all => st.body(body).map(|b| {
|
||||
let m = b.mesh();
|
||||
let groups = solidcraft_engine::doc::face_groups::face_groups_soon(&app.session.doc, b);
|
||||
let group = groups.as_ref().and_then(|g| g.group_of(*index));
|
||||
// Small on screen: only worth the look for a face picked alone.
|
||||
let small = group.is_none() && {
|
||||
let mut lo = egui::pos2(f32::INFINITY, f32::INFINITY);
|
||||
let mut hi = egui::pos2(f32::NEG_INFINITY, f32::NEG_INFINITY);
|
||||
for (t, f) in m.triangles.iter().zip(&m.tri_face) {
|
||||
if *f as usize == *index {
|
||||
for p in m.tri(t).into_iter().flatten().filter_map(|p| proj.to_screen(p)) {
|
||||
lo = lo.min(p);
|
||||
hi = hi.max(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
lo.x <= hi.x && (hi - lo).length() < 21.0
|
||||
};
|
||||
(body.clone(), groups.zip(group), small)
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
let mut bestv = Near::new(all);
|
||||
let mut beste = Near::new(all);
|
||||
for (i, b) in st.bodies.iter().enumerate() {
|
||||
if !app.session.body_visible(&b.name) {
|
||||
continue;
|
||||
}
|
||||
let inside = inside.as_ref().filter(|(body, _, _)| *body == b.name);
|
||||
let (vertex_px, edge_px) = if inside.is_some_and(|(_, _, small)| *small) { (2.0, 2.0) } else { (7.0, 6.0) };
|
||||
// Only bodies whose outline on screen is near the cursor can have an edge under it.
|
||||
if let Some((_, bb)) = bounds.get(i)
|
||||
&& screen_box(proj, bb, 8.0).is_some_and(|r| !r.contains(pos))
|
||||
@@ -1392,12 +1420,18 @@ fn pick_hits(app: &SolveApp, proj: &Proj, pos: Pos2, other_sketch_points: bool,
|
||||
if !m.edge_pickable(ei) {
|
||||
continue;
|
||||
}
|
||||
// Between two faces picked as one with the face under the pointer: not a boundary.
|
||||
if let Some((_, Some((groups, group)), _)) = inside
|
||||
&& m.edge_faces.get(ei).is_some_and(|fs| !fs.is_empty() && fs.iter().all(|f| groups.group_of(*f as usize) == Some(*group)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if last_edge != Some(ei) {
|
||||
last_edge = Some(ei);
|
||||
for v in [e.first(), e.last()].into_iter().flatten() {
|
||||
if let Some(sp) = proj.to_screen(*v) {
|
||||
let dd = sp.distance(pos);
|
||||
if dd < 7.0 && visible(*v) && bestv.wants(dd) {
|
||||
if dd < vertex_px && visible(*v) && bestv.wants(dd) {
|
||||
bestv.offer(dd, Hit::Vertex { body: b.name.clone(), point: *v });
|
||||
}
|
||||
}
|
||||
@@ -1408,21 +1442,11 @@ fn pick_hits(app: &SolveApp, proj: &Proj, pos: Pos2, other_sketch_points: bool,
|
||||
let dd = seg_dist(pos, a, c);
|
||||
// Visible where the cursor is: the edge's point under the cursor, not an end or
|
||||
// the middle, which can lie deeper than the face the cursor is on.
|
||||
if dd < 6.0 && beste.wants(dd) && visible(ray_segment_closest(o, d, *p0, *p1)) {
|
||||
if dd < edge_px && beste.wants(dd) && visible(ray_segment_closest(o, d, *p0, *p1)) {
|
||||
beste.offer(dd, Hit::Edge { body: b.name.clone(), index: ei, mid: polyline_mid(e) });
|
||||
}
|
||||
}
|
||||
}
|
||||
// The origin point, for an input that takes it: a vertex of no body, drawn over everything.
|
||||
if app.dialog.as_ref().and_then(|d| d.active_input()).is_some_and(|i| i.accept & crate::selection::ORIGIN != 0)
|
||||
&& origin_point_shown(app)
|
||||
&& let Some(sp) = proj.to_screen(Vec3::ZERO)
|
||||
{
|
||||
let dd = sp.distance(pos);
|
||||
if dd < 7.0 && bestv.wants(dd) {
|
||||
bestv.offer(dd, Hit::Vertex { body: String::new(), point: Vec3::ZERO });
|
||||
}
|
||||
}
|
||||
hits.extend(bestv.hits());
|
||||
hits.extend(beste.hits());
|
||||
// Origin axes.
|
||||
@@ -1843,6 +1867,7 @@ fn edge_of(m: &solidcraft_engine::geom::Mesh, index: usize, point: Vec3) -> Opti
|
||||
m.edges.iter().min_by(|a, b| near(a).total_cmp(&near(b))).filter(|e| near(e) < tol * 1e3)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn face_tris(sc: &mut GpuScene, m: &solidcraft_engine::geom::Mesh, face: usize, col: [u8; 4], lit: bool) {
|
||||
mesh_tris(sc, m, col, lit, |f| f as usize == face);
|
||||
}
|
||||
@@ -1877,9 +1902,25 @@ fn edge_lines(sc: &mut GpuScene, e: &[Vec3], core: Color32, halo: Color32, w: f3
|
||||
}
|
||||
|
||||
/// The outline of a highlighted face where the model hides it (dimmed).
|
||||
fn hidden_face_outline(sc: &mut GpuScene, m: &solidcraft_engine::geom::Mesh, face: usize, col: Color32) {
|
||||
/// Whether an edge (between `faces`) lies inside one thread's faces: no boundary to draw or pick.
|
||||
fn inside_group(groups: Option<&solidcraft_engine::doc::face_groups::FaceGroups>, faces: &[u32]) -> bool {
|
||||
let Some(groups) = groups else { return false };
|
||||
let mut of = faces.iter().map(|f| groups.group_of(*f as usize));
|
||||
match of.next() {
|
||||
Some(Some(g)) => faces.len() > 1 && of.all(|x| x == Some(g)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn hidden_faces_outline(
|
||||
sc: &mut GpuScene,
|
||||
m: &solidcraft_engine::geom::Mesh,
|
||||
faces: &std::collections::HashSet<usize>,
|
||||
groups: Option<&solidcraft_engine::doc::face_groups::FaceGroups>,
|
||||
col: Color32,
|
||||
) {
|
||||
for (ei, e) in m.edges.iter().enumerate() {
|
||||
let on = m.edge_faces.get(ei).is_some_and(|f| f.iter().any(|x| *x as usize == face));
|
||||
let on = m.edge_faces.get(ei).is_some_and(|f| f.iter().any(|x| faces.contains(&(*x as usize))) && !inside_group(groups, f));
|
||||
if on && m.edge_pickable(ei) {
|
||||
for p in e.windows(2) {
|
||||
sc.hidden_line(p[0].to_f32(), p[1].to_f32(), c4(col.gamma_multiply(0.45)), 1.4);
|
||||
@@ -1947,8 +1988,32 @@ fn highlight_geometry_key(app: &SolveApp) -> u64 {
|
||||
let selected = app.highlighted();
|
||||
app.session.revision.hash(&mut h);
|
||||
(std::sync::Arc::as_ptr(&crate::open_meshing::shown_world(app)) as usize).hash(&mut h);
|
||||
serde_json::to_string(&selected).unwrap_or_default().hash(&mut h);
|
||||
format!("{:?}", app.viewport.hover).hash(&mut h);
|
||||
// A thread selected is thousands of faces: they are hashed by body and index, not written
|
||||
// out every frame.
|
||||
selected.len().hash(&mut h);
|
||||
for item in &selected {
|
||||
match item {
|
||||
Sel::Face { body, index, .. } => (0u8, body, index).hash(&mut h),
|
||||
other => serde_json::to_string(other).unwrap_or_default().hash(&mut h),
|
||||
}
|
||||
}
|
||||
// A face hovered stands for the faces lit with it: moving over them (or within one) lights
|
||||
// the same, and the highlight is not built again.
|
||||
let group = match &app.viewport.hover {
|
||||
Some(Hit::Face { body, index, .. }) => app
|
||||
.session
|
||||
.world_state()
|
||||
.body(body)
|
||||
.and_then(|b| solidcraft_engine::doc::face_groups::face_groups_soon(&app.session.doc, b))
|
||||
.and_then(|g| g.of(*index))
|
||||
.and_then(|g| g.first().copied())
|
||||
.map(|first| (body.clone(), first)),
|
||||
_ => None,
|
||||
};
|
||||
match group {
|
||||
Some(group) => group.hash(&mut h),
|
||||
None => format!("{:?}", app.viewport.hover).hash(&mut h),
|
||||
}
|
||||
app.viewport.hover_feature.hash(&mut h);
|
||||
app.viewport.hover_bodies.hash(&mut h);
|
||||
// Which mesh lights a face follows how the model draws its body (see `shown_mesh`).
|
||||
@@ -2004,9 +2069,15 @@ pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene {
|
||||
// Faces lit over the model use the triangles the model shows them with.
|
||||
let shown = |b: &solidcraft_engine::doc::ModelBody| shown_mesh(app, b, &active_bodies);
|
||||
let mut sel = Vec::new();
|
||||
// Faces by body and index: a selected thread stands for thousands of them.
|
||||
let mut seen_faces: std::collections::HashSet<(String, usize)> = std::collections::HashSet::new();
|
||||
for item in app.highlighted() {
|
||||
for piece in displayed_selection(app, &item) {
|
||||
if !sel.iter().any(|x| crate::selection::same_item(x, &piece)) {
|
||||
let fresh = match &piece {
|
||||
Sel::Face { body, index, .. } => seen_faces.insert((body.clone(), *index)),
|
||||
_ => !sel.iter().any(|x| crate::selection::same_item(x, &piece)),
|
||||
};
|
||||
if fresh {
|
||||
sel.push(piece);
|
||||
}
|
||||
}
|
||||
@@ -2087,16 +2158,31 @@ pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene {
|
||||
return sc;
|
||||
}
|
||||
let mut feedback = GpuScene::default();
|
||||
// Selected faces, a pass per body however many of its faces are selected (a modelled
|
||||
// thread is thousands).
|
||||
let mut faces_of: Vec<(&str, std::collections::HashSet<usize>)> = Vec::new();
|
||||
for x in &sel {
|
||||
if let Sel::Face { body, index, .. } = x {
|
||||
match faces_of.iter_mut().find(|(b, _)| *b == body.as_str()) {
|
||||
Some((_, faces)) => {
|
||||
faces.insert(*index);
|
||||
}
|
||||
None => faces_of.push((body.as_str(), std::collections::HashSet::from([*index]))),
|
||||
}
|
||||
}
|
||||
}
|
||||
for (body, faces) in &faces_of {
|
||||
// A live preview stands in for the body: its old faces would fight with it.
|
||||
if let Some(b) = st.body(body).filter(|_| app.session.body_visible(body) && !app.preview.effective_replaced().iter().any(|r| r == *body)) {
|
||||
mesh_tris(&mut feedback, &shown(b), c4(t.sel_face), false, |f| faces.contains(&(f as usize)));
|
||||
let groups = solidcraft_engine::doc::face_groups::face_groups_soon(&s.doc, b);
|
||||
hidden_faces_outline(&mut feedback, &drawn_mesh(app, b), faces, groups.as_deref(), t.sel_edge);
|
||||
}
|
||||
}
|
||||
// Selected things.
|
||||
for x in &sel {
|
||||
match x {
|
||||
Sel::Face { body, index, .. } => {
|
||||
// A live preview stands in for the body: its old faces would fight with it.
|
||||
if let Some(b) = st.body(body).filter(|_| app.session.body_visible(body) && !app.preview.effective_replaced().contains(body)) {
|
||||
face_tris(&mut feedback, &shown(b), *index, c4(t.sel_face), false);
|
||||
hidden_face_outline(&mut feedback, &drawn_mesh(app, b), *index, t.sel_edge);
|
||||
}
|
||||
}
|
||||
Sel::Face { .. } => {}
|
||||
Sel::Body { name } => {
|
||||
if let Some(b) = st.body(name)
|
||||
&& app.session.body_visible(name)
|
||||
@@ -2222,12 +2308,21 @@ pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene {
|
||||
let k = t.hover_face_lift;
|
||||
let c = body_rgb(app, body);
|
||||
let m = drawn_mesh(app, b);
|
||||
let patch = m.surface_patch(*index);
|
||||
let lit = shown(b);
|
||||
// The face with the faces picked as one with it (a modelled thread), in one pass.
|
||||
let patch = face_patch(s, b, &m, *index);
|
||||
let mut in_patch = vec![false; m.tri_face.iter().map(|f| *f as usize + 1).max().unwrap_or(0).max(*index + 1)];
|
||||
for &f in &patch {
|
||||
face_tris(&mut feedback, &lit, f, [c.0.saturating_add(k), c.1.saturating_add(k), c.2.saturating_add(k), 255], true);
|
||||
if let Some(slot) = in_patch.get_mut(f) {
|
||||
*slot = true;
|
||||
}
|
||||
}
|
||||
for (e, _) in m.edge_faces.iter().enumerate().filter(|(_, fs)| fs.iter().any(|f| patch.contains(&(*f as usize)))) {
|
||||
let lit = shown(b);
|
||||
let col = [c.0.saturating_add(k), c.1.saturating_add(k), c.2.saturating_add(k), 255];
|
||||
mesh_tris(&mut feedback, &lit, col, true, |f| in_patch.get(f as usize).copied().unwrap_or(false));
|
||||
// Its edges, but not those between two faces of one thread: no boundary there.
|
||||
let groups = solidcraft_engine::doc::face_groups::face_groups_soon(&s.doc, b);
|
||||
let lit_face = |f: &u32| in_patch.get(*f as usize).copied().unwrap_or(false);
|
||||
for (e, _) in m.edge_faces.iter().enumerate().filter(|(_, fs)| fs.iter().any(lit_face) && !inside_group(groups.as_deref(), fs)) {
|
||||
if let Some(p) = m.edges.get(e)
|
||||
&& m.edge_pickable(e)
|
||||
{
|
||||
@@ -3148,12 +3243,49 @@ pub(crate) fn picked_selection(s: &solidcraft_engine::Session, sel: &Sel) -> Vec
|
||||
{
|
||||
return letters.into_iter().map(|index| Sel::Profile { sketch: *sketch, index }).collect();
|
||||
}
|
||||
grouped_selection(s, sel)
|
||||
selection_pieces(s, sel)
|
||||
}
|
||||
|
||||
/// Expand a visible rim or surface into the kernel pieces a command needs. The original
|
||||
/// face pick keeps its point (used by tools such as Hole and construction geometry).
|
||||
/// The faces picked as one with `face` of `b` (`m` its mesh): the pieces of its surface joined
|
||||
/// across hidden seams, and every face of a modelled thread (or of one imported face) it is part
|
||||
/// of. The thread's faces are worked out on a worker; until then the face goes with its surface.
|
||||
fn face_patch(s: &solidcraft_engine::Session, b: &solidcraft_engine::doc::ModelBody, m: &solidcraft_engine::geom::Mesh, face: usize) -> Vec<usize> {
|
||||
face_pieces(s, b, m, face, true)
|
||||
}
|
||||
|
||||
/// [`face_patch`], with the faces of the thread it is part of when `groups`.
|
||||
fn face_pieces(
|
||||
s: &solidcraft_engine::Session,
|
||||
b: &solidcraft_engine::doc::ModelBody,
|
||||
m: &solidcraft_engine::geom::Mesh,
|
||||
face: usize,
|
||||
groups: bool,
|
||||
) -> Vec<usize> {
|
||||
let mut patch = m.surface_patch(face);
|
||||
if !groups {
|
||||
return patch;
|
||||
}
|
||||
if let Some(group) = solidcraft_engine::doc::face_groups::face_groups_soon(&s.doc, b).and_then(|g| g.of(face)) {
|
||||
let mut seen: std::collections::HashSet<usize> = patch.iter().copied().collect();
|
||||
patch.extend(group.iter().copied().filter(|f| seen.insert(*f)));
|
||||
}
|
||||
patch
|
||||
}
|
||||
|
||||
pub(crate) fn grouped_selection(s: &solidcraft_engine::Session, sel: &Sel) -> Vec<Sel> {
|
||||
pieces(s, sel, true)
|
||||
}
|
||||
|
||||
/// What a click or a box puts in the selection for `sel`: as [`grouped_selection`], but a face
|
||||
/// of a modelled thread stays one item (the thread's thousands of faces are what it stands for
|
||||
/// when shown or given to a command).
|
||||
pub(crate) fn selection_pieces(s: &solidcraft_engine::Session, sel: &Sel) -> Vec<Sel> {
|
||||
pieces(s, sel, false)
|
||||
}
|
||||
|
||||
fn pieces(s: &solidcraft_engine::Session, sel: &Sel, groups: bool) -> Vec<Sel> {
|
||||
let st = s.world_state();
|
||||
match sel {
|
||||
Sel::Edge { body, index, .. } => {
|
||||
@@ -3169,21 +3301,28 @@ pub(crate) fn grouped_selection(s: &solidcraft_engine::Session, sel: &Sel) -> Ve
|
||||
Sel::Face { body, index, .. } => {
|
||||
if let Some(b) = st.body(body) {
|
||||
let m = b.mesh();
|
||||
let mut patch = m.surface_patch(*index);
|
||||
let mut patch = face_pieces(s, b, &m, *index, groups);
|
||||
patch.sort_by_key(|i| usize::from(i != index));
|
||||
// A point on each face, from one pass over the triangles.
|
||||
let wanted: std::collections::HashSet<usize> = patch.iter().copied().collect();
|
||||
let mut point: std::collections::HashMap<usize, Vec3> = std::collections::HashMap::new();
|
||||
for (t, f) in m.triangles.iter().zip(&m.tri_face) {
|
||||
let f = *f as usize;
|
||||
if f != *index
|
||||
&& !point.contains_key(&f)
|
||||
&& wanted.contains(&f)
|
||||
&& let Some([a, b, c]) = m.tri(t)
|
||||
{
|
||||
point.insert(f, (a + b + c) / 3.0);
|
||||
}
|
||||
}
|
||||
return patch
|
||||
.into_iter()
|
||||
.filter_map(|i| {
|
||||
if i == *index {
|
||||
return Some(sel.clone());
|
||||
}
|
||||
m.triangles.iter().zip(&m.tri_face).find_map(|(t, f)| {
|
||||
if *f as usize != i {
|
||||
return None;
|
||||
}
|
||||
let [a, b, c] = m.tri(t)?;
|
||||
Some(Sel::Face { body: body.clone(), index: i, point: (a + b + c) / 3.0 })
|
||||
})
|
||||
point.get(&i).map(|p| Sel::Face { body: body.clone(), index: i, point: *p })
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
@@ -3358,9 +3497,15 @@ fn box_select(app: &mut SolveApp, proj: &Proj, bx: BoxSel, add: bool) {
|
||||
}
|
||||
}
|
||||
let mut grouped = Vec::new();
|
||||
// Faces by body and index: a box over a thread takes thousands of them.
|
||||
let mut faces: std::collections::HashSet<(String, usize)> = std::collections::HashSet::new();
|
||||
for item in out {
|
||||
for piece in grouped_selection(&app.session, &item) {
|
||||
if !grouped.iter().any(|x| crate::selection::same_item(x, &piece)) {
|
||||
for piece in selection_pieces(&app.session, &item) {
|
||||
let fresh = match &piece {
|
||||
Sel::Face { body, index, .. } => faces.insert((body.clone(), *index)),
|
||||
_ => !grouped.iter().any(|x| crate::selection::same_item(x, &piece)),
|
||||
};
|
||||
if fresh {
|
||||
grouped.push(piece);
|
||||
}
|
||||
}
|
||||
@@ -3375,15 +3520,11 @@ fn box_select(app: &mut SolveApp, proj: &Proj, bx: BoxSel, add: bool) {
|
||||
let _ = app.run("select.set", json!({"items": items, "add": add}));
|
||||
}
|
||||
|
||||
/// Whether the origin point is drawn (the Origin shown and its point not hidden).
|
||||
fn origin_point_shown(app: &SolveApp) -> bool {
|
||||
app.origin_visible() && !app.session.visibility.hidden_origin.iter().any(|h| h == "O")
|
||||
}
|
||||
|
||||
/// Screen-space dots: the origin point, and hovered or selected body vertices.
|
||||
fn points_2d(app: &SolveApp, painter: &egui::Painter, proj: &Proj) {
|
||||
let t = Tokens::get();
|
||||
if origin_point_shown(app)
|
||||
if app.origin_visible()
|
||||
&& !app.session.visibility.hidden_origin.iter().any(|h| h == "O")
|
||||
&& let Some(o) = proj.to_screen(Vec3::ZERO)
|
||||
{
|
||||
painter.circle(o, 4.5, t.origin_point, Stroke::new(1.0, Color32::from_gray(110)));
|
||||
|
||||
@@ -60,15 +60,6 @@ pub struct Section {
|
||||
pub ids: &'static [&'static str],
|
||||
}
|
||||
|
||||
/// Parameters and Configurations stay on every design tab they were on before the ribbon
|
||||
/// redesign (MODEL and SHEET METAL), on SKETCH while editing a sketch, and in MANAGE, their
|
||||
/// canonical home.
|
||||
const CONFIGURE: &[&str] = &["parameters.change", "config.table", "config.configure"];
|
||||
|
||||
/// Commands that stay for agents, MCP and scripts but are not offered to people: the sketch solves
|
||||
/// itself after every edit, so a Solve button (and the search hit for it) only confuses.
|
||||
pub const AGENT_ONLY: &[&str] = &["sketch.solve"];
|
||||
|
||||
pub const SECTIONS: &[Section] = &[
|
||||
Section {
|
||||
tab: "MODEL",
|
||||
@@ -89,10 +80,7 @@ pub const SECTIONS: &[Section] = &[
|
||||
promoted: 3,
|
||||
ids: &["solid.move", "solid.mirror", "solid.pattern.rectangular", "solid.align", "solid.pattern.circular", "solid.pattern.path"],
|
||||
},
|
||||
Section { tab: "MODEL", panel: "CONFIGURE", promoted: 2, ids: CONFIGURE },
|
||||
Section { tab: "MODEL", panel: "CONSTRUCT", promoted: 1, ids: &["construct.plane.offset"] },
|
||||
// Sketches drive surfaces too: New Sketch leads the tab, as on MODEL and SHEET METAL.
|
||||
Section { tab: "SURFACE", panel: "SKETCH", promoted: 1, ids: &["sketch.create"] },
|
||||
Section { tab: "SURFACE", panel: "CREATE", promoted: 4, ids: &["surface.extrude", "surface.revolve", "surface.sweep", "surface.loft"] },
|
||||
Section { tab: "SURFACE", panel: "EDIT", promoted: 4, ids: &["surface.trim", "surface.untrim", "surface.extend", "surface.stitch"] },
|
||||
Section { tab: "SURFACE", panel: "CONVERT", promoted: 2, ids: &["surface.thicken", "mesh.convert"] },
|
||||
@@ -244,11 +232,7 @@ pub const SECTIONS: &[Section] = &[
|
||||
"canvas.insert",
|
||||
],
|
||||
},
|
||||
// Sketch dimensions are driven by parameters, so they are one click away while sketching.
|
||||
Section { tab: "SKETCH", panel: "CONFIGURE", promoted: 2, ids: CONFIGURE },
|
||||
Section { tab: "SKETCH", panel: "FINISH SKETCH", promoted: 1, ids: &["sketch.finish"] },
|
||||
// New Sketch leads the tab, as on MODEL: a sheet part starts from a sketch (#3250).
|
||||
Section { tab: "SHEET METAL", panel: "SKETCH", promoted: 1, ids: &["sketch.create"] },
|
||||
Section {
|
||||
tab: "SHEET METAL",
|
||||
panel: "CREATE",
|
||||
@@ -258,7 +242,6 @@ pub const SECTIONS: &[Section] = &[
|
||||
Section { tab: "SHEET METAL", panel: "FLAT", promoted: 3, ids: &["sheet.unfold", "sheet.refold", "sheet.flat_pattern"] },
|
||||
Section { tab: "SHEET METAL", panel: "OUTPUT", promoted: 2, ids: &["sheet.export_dxf", "sheet.export_bend_table"] },
|
||||
Section { tab: "SHEET METAL", panel: "RULES", promoted: 1, ids: &["sheet.manage_rules"] },
|
||||
Section { tab: "SHEET METAL", panel: "CONFIGURE", promoted: 2, ids: CONFIGURE },
|
||||
Section { tab: "RENDER", panel: "SCENE", promoted: 2, ids: &["render.scene"] },
|
||||
Section { tab: "RENDER", panel: "IMAGE", promoted: 1, ids: &["render.start"] },
|
||||
];
|
||||
@@ -362,8 +345,6 @@ pub fn destination(c: &CommandSpec) -> Option<(&'static str, &'static str)> {
|
||||
let primary = match c.id {
|
||||
"sheet.manage_rules" => Some(("MANAGE", "RULES")),
|
||||
"sheet.convert" => Some(("MODEL", "MODIFY")),
|
||||
"parameters.change" => Some(("MANAGE", "PARAMETERS")),
|
||||
"config.table" | "config.configure" => Some(("MANAGE", "CONFIGURATIONS")),
|
||||
_ => None,
|
||||
};
|
||||
primary
|
||||
@@ -451,9 +432,9 @@ pub fn visible_tabs(app: &crate::SolveApp) -> Vec<&'static str> {
|
||||
if app.session.active_sketch.is_some() {
|
||||
tabs.push("SKETCH");
|
||||
}
|
||||
// Always reachable, as before the ribbon redesign: a sheet-metal part starts from an
|
||||
// ordinary sketch or solid, so the tab cannot wait for a sheet body.
|
||||
tabs.push("SHEET METAL");
|
||||
if sheet_body(app).is_some() {
|
||||
tabs.push("SHEET METAL");
|
||||
}
|
||||
tabs
|
||||
}
|
||||
|
||||
@@ -635,8 +616,6 @@ mod tests {
|
||||
("INSERT", "FILES", "component.insert_design"),
|
||||
("ASSEMBLE", "COMPONENTS", "component.insert_design"),
|
||||
("SHEET METAL", "CREATE", "sheet.convert"),
|
||||
("SHEET METAL", "SKETCH", "sketch.create"),
|
||||
("SURFACE", "SKETCH", "sketch.create"),
|
||||
("SKETCH", "REFERENCE", "canvas.insert"),
|
||||
] {
|
||||
assert!(layout(tab, panel, &specs).unwrap().0.iter().any(|c| c.id == id));
|
||||
@@ -646,9 +625,7 @@ mod tests {
|
||||
#[test]
|
||||
fn contextual_tabs_follow_the_active_body_and_allow_other_tabs() {
|
||||
let mut h = crate::scenario::Harness::new();
|
||||
let mut fresh = TABS.to_vec();
|
||||
fresh.push("SHEET METAL");
|
||||
assert_eq!(visible_tabs(&h.app), fresh, "SHEET METAL is reachable before any sheet body exists");
|
||||
assert_eq!(visible_tabs(&h.app), TABS);
|
||||
h.app.run("sketch.create", json!({"plane":"XY"})).unwrap();
|
||||
assert_eq!(h.app.ui.tab, "SKETCH");
|
||||
h.app.run("sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[40,30]})).unwrap();
|
||||
@@ -668,69 +645,15 @@ mod tests {
|
||||
h.app.run("solid.box", json!({"body_name":"Solid", "operation":"new", "length":10, "width":10, "height":10})).unwrap();
|
||||
h.app.run("select.set", json!({"items":[{"type":"body","name":"Solid"}]})).unwrap();
|
||||
sync_context(&mut h.app);
|
||||
assert!(visible_tabs(&h.app).contains(&"SHEET METAL"), "the tab stays reachable off a sheet body");
|
||||
assert!(sheet_body(&h.app).is_none());
|
||||
assert!(!visible_tabs(&h.app).contains(&"SHEET METAL"));
|
||||
h.app.run("select.set", json!({"items":[{"type":"body","name":"Sheet"}]})).unwrap();
|
||||
sync_context(&mut h.app);
|
||||
assert_eq!(h.app.ui.tab, "SHEET METAL");
|
||||
}
|
||||
|
||||
/// Parameters and Configurations are on the design tabs they were on before the redesign, and a
|
||||
/// fresh document reaches Sheet Metal (to flange a sketch or convert a solid) by its tab.
|
||||
#[test]
|
||||
fn parameters_and_configurations_are_on_model_and_sheet_metal_and_the_sheet_tab_opens_fresh() {
|
||||
let specs = solidcraft_engine::command_specs();
|
||||
for tab in ["MODEL", "SHEET METAL", "SKETCH", "MANAGE"] {
|
||||
let ids = panel_ids(tab, &specs);
|
||||
assert!(ids.contains(&"parameters.change"), "{tab}: Parameters");
|
||||
assert!(ids.contains(&"config.table"), "{tab}: Configurations");
|
||||
}
|
||||
for tab in ["MODEL", "SHEET METAL", "SKETCH"] {
|
||||
let (commands, n) = layout(tab, "CONFIGURE", &specs).unwrap();
|
||||
assert_eq!(commands.iter().take(n).map(|c| c.id).collect::<Vec<_>>(), ["parameters.change", "config.table"]);
|
||||
}
|
||||
let mut h = crate::scenario::Harness::new();
|
||||
assert!(sheet_body(&h.app).is_none());
|
||||
h.step(&json!({"click":{"handle":"tab:SHEET METAL"}})).unwrap();
|
||||
h.frames(2);
|
||||
assert_eq!(h.app.ui.tab, "SHEET METAL");
|
||||
let specs = solidcraft_engine::command_specs();
|
||||
let (create, _) = layout("SHEET METAL", "CREATE", &specs).unwrap();
|
||||
assert!(create.iter().any(|c| c.id == "sheet.convert"), "Convert to Sheet Metal is in the Sheet Metal tab's Create panel");
|
||||
for id in ["sheet.flange", "parameters.change", "config.table"] {
|
||||
assert!(crate::scenario::handle_at(&format!("button:{id}")).is_some(), "{id} is a button on the fresh Sheet Metal tab");
|
||||
}
|
||||
h.step(&json!({"click":{"handle":"button:parameters.change"}})).unwrap();
|
||||
assert!(h.app.params.is_some(), "Parameters opens from the Sheet Metal tab");
|
||||
assert_eq!(h.app.ui.tab, "SHEET METAL", "and the tab stays");
|
||||
h.step(&json!({"click":{"handle":"params:close"}})).unwrap();
|
||||
h.app.run("sketch.create", json!({"plane":"XY"})).unwrap();
|
||||
h.frames(2);
|
||||
assert_eq!(h.app.ui.tab, "SKETCH");
|
||||
for id in ["parameters.change", "config.table"] {
|
||||
assert!(crate::scenario::handle_at(&format!("button:{id}")).is_some(), "{id} is a button on the Sketch tab");
|
||||
}
|
||||
h.app.finish_sketch();
|
||||
h.step(&json!({"click":{"handle":"tab:MODEL"}})).unwrap();
|
||||
h.frames(2);
|
||||
h.step(&json!({"click":{"handle":"button:config.table"}})).unwrap();
|
||||
assert!(matches!(
|
||||
h.app.dialog.as_ref().map(|d| &d.kind),
|
||||
Some(crate::dialogs::Kind::Motion(crate::dialogs_motion::Mo::Configurations { .. }))
|
||||
));
|
||||
assert_eq!(h.app.ui.tab, "MODEL", "Configurations opens from the Model tab without leaving it");
|
||||
}
|
||||
|
||||
fn panel_ids(tab: &str, specs: &[&CommandSpec]) -> Vec<&'static str> {
|
||||
SECTIONS.iter().filter(|s| s.tab == tab).flat_map(|s| layout(tab, s.panel, specs).unwrap().0).map(|c| c.id).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn starts_palette_and_control_use_the_new_destinations() {
|
||||
let mut h = crate::scenario::Harness::new();
|
||||
// Parameters is also on MODEL, so a start from there stays put; from SURFACE it goes home.
|
||||
h.app.ui.tab = "SURFACE".into();
|
||||
h.frames(2);
|
||||
for (id, tab) in [("parameters.change", "MANAGE"), ("solid.box", "MODEL"), ("surface.patch", "SURFACE")] {
|
||||
h.step(&json!({"start":id})).unwrap();
|
||||
assert_eq!(h.app.ui.tab, tab, "{id}");
|
||||
@@ -854,117 +777,4 @@ mod tests {
|
||||
}
|
||||
assert_eq!(h.app.session.world_state().bodies.len(), 2, "the STEP file's body is inserted");
|
||||
}
|
||||
|
||||
/// Every way into a sketch (New Sketch on the ribbon then a plane, a double-click in the
|
||||
/// timeline or the browser, Edit Sketch in the browser's menu) opens the SKETCH tab and looks
|
||||
/// at the sketch; Finish Sketch (palette or ribbon) lands on MODEL with the earlier view back
|
||||
/// and the sketch still listed, as before the ribbon redesign.
|
||||
#[test]
|
||||
fn entering_and_finishing_a_sketch_keeps_the_tab_view_and_history() {
|
||||
let iso = json!({"camera": {"yaw_deg": -45, "pitch_deg": 35}});
|
||||
let top = json!({"camera": {"yaw_deg": 0, "pitch_deg": 90}});
|
||||
let expect = |h: &mut crate::scenario::Harness, e: &serde_json::Value, what: &str| {
|
||||
h.frames(3);
|
||||
crate::scenario::check(h, e).unwrap_or_else(|err| panic!("{what}: {err}"));
|
||||
};
|
||||
let mut h = crate::scenario::Harness::new();
|
||||
h.call("ui.view", json!({"view": "iso"}));
|
||||
h.frames(3);
|
||||
h.step(&json!({"click": {"handle": "button:sketch.create"}})).unwrap();
|
||||
h.step(&json!({"click": {"plane": "XY"}})).unwrap();
|
||||
expect(&mut h, &top, "New Sketch on XY");
|
||||
assert_eq!(h.app.ui.tab, "SKETCH");
|
||||
h.app.run("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]})).unwrap();
|
||||
h.step(&json!({"click": {"handle": "sketch_palette:finish"}})).unwrap();
|
||||
expect(&mut h, &json!({"sketching": false, "errors": 0}), "Finish");
|
||||
expect(&mut h, &iso, "Finish puts the view back");
|
||||
assert_eq!(h.app.ui.tab, "MODEL");
|
||||
assert!(crate::scenario::handle_at("timeline:Sketch1").is_some() && crate::scenario::handle_at("row:Sketch1").is_some());
|
||||
|
||||
let entries = [
|
||||
("timeline double-click", vec![json!({"click": {"handle": "timeline:Sketch1"}, "double": true})]),
|
||||
("browser double-click", vec![json!({"click": {"handle": "row:Sketch1"}, "double": true})]),
|
||||
(
|
||||
"browser Edit Sketch",
|
||||
vec![json!({"click": {"handle": "row:Sketch1"}, "button": "right"}), json!({"click": {"handle": "menu:ui.editSketch"}})],
|
||||
),
|
||||
];
|
||||
for (how, steps) in entries {
|
||||
for s in steps {
|
||||
h.frames(3);
|
||||
h.step(&s).unwrap_or_else(|e| panic!("{how}: {e}"));
|
||||
}
|
||||
expect(&mut h, &json!({"sketching": true}), how);
|
||||
expect(&mut h, &top, how);
|
||||
assert_eq!(h.app.ui.tab, "SKETCH", "{how}");
|
||||
h.step(&json!({"click": {"handle": "button:sketch.finish"}})).unwrap();
|
||||
expect(&mut h, &json!({"sketching": false}), how);
|
||||
expect(&mut h, &iso, how);
|
||||
assert_eq!(h.app.ui.tab, "MODEL", "{how}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Escape and Enter, pressed one at a time, never leave a sketch (#1804); Undo right after
|
||||
/// Finish reopens it, and a second Undo removes it and leaves the SKETCH tab.
|
||||
#[test]
|
||||
fn keys_keep_a_sketch_open_and_undo_after_finish_reopens_it() {
|
||||
let mut h = crate::scenario::Harness::new();
|
||||
h.frames(3);
|
||||
h.step(&json!({"start": "sketch.create"})).unwrap();
|
||||
h.step(&json!({"click": {"plane": "XY"}})).unwrap();
|
||||
h.app.run("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]})).unwrap();
|
||||
for key in [json!({"key": "Escape"}), json!({"key": "Escape"}), json!({"key": "Enter"}), json!({"key": "Enter", "cmd": true})] {
|
||||
h.step(&key).unwrap();
|
||||
// Well apart, so two presses are never a quick double press.
|
||||
h.frames(60);
|
||||
assert!(h.app.session.active_sketch.is_some(), "{key}");
|
||||
assert_eq!(h.app.ui.tab, "SKETCH", "{key}");
|
||||
}
|
||||
h.step(&json!({"click": {"handle": "sketch_palette:finish"}})).unwrap();
|
||||
h.frames(2);
|
||||
h.step(&json!({"key": "Z", "cmd": true})).unwrap();
|
||||
h.frames(2);
|
||||
assert!(h.app.session.active_sketch.is_some(), "Undo after Finish reopens the sketch");
|
||||
assert_eq!(h.app.ui.tab, "SKETCH");
|
||||
h.step(&json!({"key": "Z", "cmd": true})).unwrap();
|
||||
h.frames(2);
|
||||
assert!(h.app.session.active_sketch.is_none());
|
||||
assert_eq!(h.app.ui.tab, "MODEL");
|
||||
}
|
||||
|
||||
/// New Sketch is on the SHEET METAL tab, as it was before the ribbon redesign, and a sketch
|
||||
/// started there stays on its tab until it opens.
|
||||
#[test]
|
||||
fn new_sketch_starts_from_the_sheet_metal_tab() {
|
||||
let mut h = crate::scenario::Harness::new();
|
||||
h.app.run("sketch.create", json!({"plane": "XY"})).unwrap();
|
||||
h.app.run("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]})).unwrap();
|
||||
h.app.run("sketch.finish", json!({})).unwrap();
|
||||
h.app.run("sheet.flange", json!({"name": "Sheet", "body_name": "Sheet"})).unwrap();
|
||||
h.frames(3);
|
||||
assert_eq!(h.app.ui.tab, "SHEET METAL");
|
||||
h.step(&json!({"click": {"handle": "button:sketch.create"}})).unwrap();
|
||||
h.frames(2);
|
||||
assert_eq!(h.app.ui.tab, "SHEET METAL", "New Sketch is on this tab, so it stays");
|
||||
h.step(&json!({"click": {"plane": "XZ"}})).unwrap();
|
||||
h.frames(2);
|
||||
assert!(h.app.session.active_sketch.is_some());
|
||||
assert_eq!(h.app.ui.tab, "SKETCH");
|
||||
}
|
||||
|
||||
/// New Sketch is on the SURFACE tab too, and a sketch started there stays on that tab until
|
||||
/// it opens.
|
||||
#[test]
|
||||
fn new_sketch_starts_from_the_surface_tab() {
|
||||
let mut h = crate::scenario::Harness::new();
|
||||
h.step(&json!({"click": {"handle": "tab:SURFACE"}})).unwrap();
|
||||
h.frames(2);
|
||||
h.step(&json!({"click": {"handle": "button:sketch.create"}})).unwrap();
|
||||
h.frames(2);
|
||||
assert_eq!(h.app.ui.tab, "SURFACE", "New Sketch is on this tab, so it stays");
|
||||
h.step(&json!({"click": {"plane": "XY"}})).unwrap();
|
||||
h.frames(2);
|
||||
assert!(h.app.session.active_sketch.is_some());
|
||||
assert_eq!(h.app.ui.tab, "SKETCH");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,7 +95,7 @@
|
||||
"click": {"handle": "appbar:file"}
|
||||
},
|
||||
{
|
||||
"widget": "Export STL\u2026"
|
||||
"widget": "Save as mesh\u2026"
|
||||
},
|
||||
{
|
||||
"expect": {
|
||||
|
||||
@@ -161,7 +161,7 @@ fn docked_ribbon_geometry_and_search() {
|
||||
|
||||
#[test]
|
||||
fn finish_sketch_stays_at_the_right_when_groups_collapse() {
|
||||
use solidcraft_ui_egui::scenario::{count_of, handle_at};
|
||||
use solidcraft_ui_egui::scenario::handle_at;
|
||||
for layout in ["docked", "floating"] {
|
||||
let mut h = Harness::new();
|
||||
h.call("ui.set", json!({"layout":layout}));
|
||||
@@ -172,16 +172,7 @@ fn finish_sketch_stays_at_the_right_when_groups_collapse() {
|
||||
let ribbon = rect_of("toolbar").unwrap();
|
||||
let exit = rect_of("ribbon:section:SKETCH:FINISH SKETCH").unwrap();
|
||||
let finish = rect_of("button:sketch.finish").unwrap();
|
||||
// Finish follows the last sketch panel; once panels spill into the » menu it sits at
|
||||
// the right end, after it.
|
||||
if count_of("toolbar_more").unwrap_or(0.0) > 0.0 {
|
||||
assert_eq!(exit.right(), ribbon.right() - 4.0, "{layout} at {width}");
|
||||
} else {
|
||||
assert!(exit.right() <= ribbon.right() - 4.0, "{layout} at {width}");
|
||||
let last = rect_of("panel:SKETCH:CONFIGURE").or_else(|| rect_of("panel:SKETCH:REFERENCE")).unwrap();
|
||||
let group = rect_of("panel:SKETCH:FINISH SKETCH").unwrap();
|
||||
assert!(group.left() - last.right() < 16.0, "{layout} at {width}: Finish follows the last panel");
|
||||
}
|
||||
assert_eq!(exit.right(), ribbon.right() - 4.0);
|
||||
assert!(ribbon.contains_rect(finish));
|
||||
assert!(finish.bottom() < exit.top());
|
||||
assert!(handle_at("tab:SKETCH").is_some(), "the selected contextual tab scrolls into view");
|
||||
|
||||
@@ -77,8 +77,8 @@ Pull requests skip a few heavy tests (each takes one to twelve minutes); they ru
|
||||
`main`, nightly, and in `cargo xtask test`:
|
||||
|
||||
- `solidcraft-engine`: `tests::hostile_params_never_panic`, everything in `tests::robustness` and
|
||||
the seeds of `tests::robustness_goldens` (`seed_00` … `seed_95`; pull requests that change the kernel, truck or
|
||||
the goldens run all but the slowest, `SLOW_SEEDS` in `ci.yml`),
|
||||
the seeds of `tests::robustness_goldens` (`seed_00` … `seed_95`; pull requests that can change
|
||||
them run all but the slowest, `SLOW_SEEDS` in `ci.yml`),
|
||||
`pattern_suppress_tests::enclosure_arc_extinction_keeps_a_real_sharp_inner_lip_after_resize_and_reopen`,
|
||||
`pattern_suppress_tests::enclosure_datums_follow_wall_height_and_board_depth_with_material_proofs`,
|
||||
`cmd::plastic::tests::enclosure_snap_fit_follows_resized_front_wall`, the `atomic_commands` contract tests
|
||||
|
||||
@@ -38,9 +38,8 @@ A 3MF project saved by a slicer comes in too, also when it keeps its objects in
|
||||
their own inside the file (the 3MF Production extension): each object on the build plate becomes
|
||||
a mesh body, with its parts where the slicer placed them.
|
||||
|
||||
**File → Export STL…** and **File → Export 3MF…** (also on the Mesh tab under Modify as Save as
|
||||
mesh, and in the right-click menu of a body) open the same dialog with that format chosen; it saves
|
||||
the selected bodies as STL, 3MF or 3MF with face tags (below), and you can change the format there. With **Send to slicer** ticked, it writes the file to
|
||||
**File → Save as mesh…** (also on the Mesh tab under Modify, and in the right-click menu of a
|
||||
body) saves the selected bodies as STL, 3MF or 3MF with face tags (below). With **Send to slicer** ticked, it writes the file to
|
||||
a temporary folder and opens it in the chosen slicer instead of asking for a file name. The slicer
|
||||
list shows the slicers found on the computer with their icons; **Custom…** adds any other program
|
||||
to the top of the list (kept between runs; hover an entry you added and press Delete to remove it).
|
||||
@@ -48,7 +47,7 @@ to the top of the list (kept between runs; hover an entry you added and press De
|
||||
Closed mechanical meshes with a constant cross-section can be rebuilt as solids with the
|
||||
`mesh.convert` command (command palette, scripts and the control channel).
|
||||
|
||||
**File → Export 3MF…** with the format changed to **3MF with face tags** (`file.export` or `file.save_mesh` with `format: "3mf-tagged"`) writes an
|
||||
**File → Save as mesh…** with the format **3MF with face tags** (`file.export` or `file.save_mesh` with `format: "3mf-tagged"`) writes an
|
||||
ordinary 3MF in which every triangle also names the B-rep face it lies on and every coordinate
|
||||
is the tessellation's own double-precision value. Meshing and analysis tools can use the tags to
|
||||
keep a model's faces (for loads, boundary conditions or feature edges); other 3MF readers ignore
|
||||
@@ -62,9 +61,8 @@ written as STL files next to the `.urdf`. See [`docs/urdf.md`](https://github.co
|
||||
Saves are atomic: a crash at any moment leaves either the old file or the new one, and the
|
||||
replaced version is kept as `<file>.bak`. A save keeps the file's permissions, and a design
|
||||
opened through a symbolic link (a synced folder linked into a project) is saved into the file the
|
||||
link points to, so the link stays. Unsaved changes in every open tab are autosaved to separate
|
||||
entries in a recovery folder, and the next launch offers to recover each design. Saving or
|
||||
closing one tab removes only its recovery entry. Older design files are upgraded on open, and files
|
||||
link points to, so the link stays. Unsaved changes are autosaved to a recovery folder,
|
||||
and the next launch offers to recover them. Older design files are upgraded on open, and files
|
||||
from a newer version are refused with a message.
|
||||
|
||||
**Save** writes a container by default; files named `.json` keep JSON on subsequent saves.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Sheet metal
|
||||
|
||||
MODEL → MODIFY offers Convert to Sheet Metal. The SHEET METAL tab is always available (it is highlighted
|
||||
and selected when the active body is a sheet), and builds parts from a sheet of constant thickness under a **sheet metal rule**
|
||||
MODEL → MODIFY offers Convert to Sheet Metal. The contextual SHEET METAL tab appears
|
||||
when the active body is a sheet, and builds parts from a sheet of constant thickness under a **sheet metal rule**
|
||||
(thickness, bend radius, K-factor), set in **Sheet Metal Rules** (`sheet.manage_rules`).
|
||||
|
||||
- **Flange** (`sheet.flange`): a base flange from a sketch profile, a contour flange from an open
|
||||
|
||||
@@ -8,8 +8,8 @@
|
||||
unsaved changes). On the right: Report a bug, Help (?), Preferences (which hold the theme) and the
|
||||
window's buttons.
|
||||
- **Toolbar.** The workspace switcher (DESIGN) sits on the left. The tabs (MODEL, SURFACE,
|
||||
ASSEMBLE, INSERT, INSPECT, MANAGE, VIEW and SHEET METAL) hold sections of commands. SKETCH appears while
|
||||
editing a sketch; SHEET METAL is always there and is highlighted for the active sheet body. Both select automatically
|
||||
ASSEMBLE, INSERT, INSPECT, MANAGE and VIEW) hold sections of commands. SKETCH appears while
|
||||
editing a sketch; SHEET METAL appears for the active sheet body. Both select automatically
|
||||
when entered, and the other tabs remain available. Click a
|
||||
panel's name for all its commands. Drag a command from the dropdown onto a panel's label
|
||||
or empty space to append it; the insertion line shows its destination. Drop onto an existing
|
||||
|
||||
@@ -74,7 +74,7 @@ MCP server sends its folders this way on every request ([mcp.md](mcp.md)). Witho
|
||||
|---|---|---|
|
||||
| `engine.execute` | `command`: command id, `params`: JSON object | the command's result |
|
||||
| `engine.script` | `commands`: `[{command, params}, …]` | results, stops at the first error |
|
||||
| `engine.batch` | `commands`: `[{command, params}, …]` (at most 10 000), `rollback?`: bool (default true), `timings?`, `profile?`: bool (default false) | `{completed, results, undone}`, plus `failed: {index, command, error}` when a step fails, and with `timings` `timings: [{index, command, ms}]` (the failing step included) and `total_ms`; `profile` adds each step's `profile: {boolean_ms, tessellate_ms, other_ms}`. Runs the steps in one request, so within one frame, each as `engine.execute` runs it. The first failure stops the batch, and with `rollback` the design goes back to how it was before it (`undone`: the steps taken back, `rolled_back`: whether the design is back as it was, `false` only when the checkpoint could not restore it). Refused before anything runs, with an error starting `engine.batch unavailable`, while the agent cursor is shown or when a step loads a file (`doc.open`, `file.insert_step`, `file.insert_mesh`). Send such steps one by one. Answered when done, for up to 3600 s |
|
||||
| `engine.batch` | `commands`: `[{command, params}, …]` (at most 10 000), `rollback?`: bool (default true), `timings?`, `profile?`: bool (default false) | `{completed, results, undone}`, plus `failed: {index, command, error}` when a step fails, and with `timings` `timings: [{index, command, ms}]` (the failing step included) and `total_ms`; `profile` adds each step's `profile: {boolean_ms, tessellate_ms, other_ms}`. Runs the steps in one request, so within one frame, each as `engine.execute` runs it. The first failure stops the batch, and with `rollback` the design goes back to how it was before it (`undone`: the steps taken back). Refused before anything runs, with an error starting `engine.batch unavailable`, while the agent cursor is shown or when a step loads a file (`doc.open`, `file.insert_step`, `file.insert_mesh`). Send such steps one by one. Answered when done, for up to 3600 s |
|
||||
| `engine.commands` | — | every command: id, label, tab, panel, icon, shortcut, params doc, enabled |
|
||||
| `document.inspect` | `measure?`: bool | parameters, timeline (errors, timings), bodies, sketches, selection (assembly joints: `engine.execute` `joint.inspect {joint?}`, which reads only: each joint's two origins with the occurrence, the snap as saved, the feature, face, edge or sketch curve its names refer to, and whether it resolves or why not; kind, offset, angle, flip, values, limits, expressions and motion links) |
|
||||
|
||||
@@ -140,7 +140,7 @@ labels; `prefs:measure_axis_distances` identifies the checkbox.
|
||||
| `ui.sketchToScreen` | `points`: `[[x, y]…]` in active-sketch coordinates | their screen points (null when behind the camera) |
|
||||
| `ui.dialogInput` | `index` | what clicking an input's Select chip does: picks go to that input |
|
||||
| `ui.at` | `world: [x,y,z]` \| `sketch: [x,y]` \| `plane: "XY"` \| `axis: "Z"` \| `dimension: "d1"` (its value text) \| `handle: "arrow"` (a manipulator handle, see `scenario::publish_handle`) | the screen point (a scenario step's target; see `crates/ui-egui/src/scenario.rs`) |
|
||||
| `ui.handles` | `prefix?` | the handles drawn last frame, `[{name, x, y}]`: toolbar buttons and drop-down items `toolbar:<command id>` (the button alone: `button:<command id>`; a drop-down row: `dropdown:<command id>`, highlighted `dropdown_hot:<command id>`, its pin `dropdown_pin:<command id>`; Customize Toolbar's check boxes `customize:<command id>`), ribbon tabs `tab:<name>` (MODEL, SURFACE, ASSEMBLE, INSERT, INSPECT, MANAGE, VIEW, SHEET METAL; contextual SKETCH; workspace RENDER), panel labels `panel:<tab>:<panel>` (also `ribbon:section:<TAB>:<SECTION>`), document overflow list `tab:overflow`, workspace column `ribbon:workspace`, command-search launcher `ribbon:search`, browser rows `row:<label>` and fold arrows `fold:<label>`, manipulator handles; signed-axis tips `axis_view:z`, `axis_view:-y`; optional cube facets `navigation_cube:top`, `navigation_cube:top_front_right`, controls `navigation_cube:control:home` (and other actions), plus signed-axis aliases for visible cube faces; Preferences navigator picker `prefs:navigator`, options `prefs:navigator:Signed axes` and `prefs:navigator:Cube`; in the Motion Study dialog, where the chart puts its first and last step `motion:chart_start` and `motion:chart_end`, the Check collisions button `motion:check` and each collision found `motion:collision:<n>` |
|
||||
| `ui.handles` | `prefix?` | the handles drawn last frame, `[{name, x, y}]`: toolbar buttons and drop-down items `toolbar:<command id>` (the button alone: `button:<command id>`; a drop-down row: `dropdown:<command id>`, highlighted `dropdown_hot:<command id>`, its pin `dropdown_pin:<command id>`; Customize Toolbar's check boxes `customize:<command id>`), ribbon tabs `tab:<name>` (MODEL, SURFACE, ASSEMBLE, INSERT, INSPECT, MANAGE, VIEW; contextual SKETCH and SHEET METAL; workspace RENDER), panel labels `panel:<tab>:<panel>` (also `ribbon:section:<TAB>:<SECTION>`), document overflow list `tab:overflow`, workspace column `ribbon:workspace`, command-search launcher `ribbon:search`, browser rows `row:<label>` and fold arrows `fold:<label>`, manipulator handles; signed-axis tips `axis_view:z`, `axis_view:-y`; optional cube facets `navigation_cube:top`, `navigation_cube:top_front_right`, controls `navigation_cube:control:home` (and other actions), plus signed-axis aliases for visible cube faces; Preferences navigator picker `prefs:navigator`, options `prefs:navigator:Signed axes` and `prefs:navigator:Cube`; in the Motion Study dialog, where the chart puts its first and last step `motion:chart_start` and `motion:chart_end`, the Check collisions button `motion:check` and each collision found `motion:collision:<n>` |
|
||||
| `ui.editFeature` | `feature` (id or name) | what double-clicking a timeline item does: rolls back to it and opens its dialog filled in (sketches open in sketch mode) |
|
||||
| `ui.scroll` | `x`, `y`, `delta?` | wheel zoom at the cursor |
|
||||
| `ui.key` | `key` (egui key name, `Enter`, `Escape`…), `cmd?`, `shift?` | |
|
||||
|
||||
@@ -7,7 +7,7 @@ A tessellated body loses its faces: a plain mesh says where the surface is, not
|
||||
each triangle came from. Downstream tools that mesh or analyse a part need that back. They apply
|
||||
loads and boundary conditions to faces, keep face boundaries as feature edges, and group
|
||||
results by face. SolidCraft therefore exports a 3MF in which every triangle carries the index of
|
||||
the B-rep face it lies on (**File → Export 3MF…**, then the format **3MF with face tags**, or `file.export` with
|
||||
the B-rep face it lies on (**File → Save as mesh…** (format **3MF with face tags**), or `file.export` with
|
||||
`format: "3mf-tagged"`).
|
||||
|
||||
## Why 3MF
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# UI localization
|
||||
|
||||
SolidCraft embeds its translations and works offline. English, Czech, Danish, German, English (UK), Spanish, French, Galician, Italian,
|
||||
SolidCraft embeds its translations and works offline. English, Czech, Danish, German, Spanish, French, Galician, Italian,
|
||||
Japanese, Korean, Malay, Polish, Brazilian Portuguese, Russian, Turkish, Ukrainian and Chinese are currently registered in `crates/ui-egui/src/i18n.rs`. Adding a language requires an
|
||||
embedded catalog and one registration there; the preferences selector and validation use the same
|
||||
registry.
|
||||
@@ -31,12 +31,6 @@ entry has a note for translators: what the term must not be confused with. Its "
|
||||
than one meaning" table lists the English words that need a separate catalogue entry for each
|
||||
meaning (Construction, Flat, Round, Normal, Gap, Clearance).
|
||||
|
||||
## English (UK)
|
||||
|
||||
`en-GB.json` holds only the English messages whose spelling differs in UK English (Centre,
|
||||
Customise, Organisation, Licence, colours, …); every other message falls back to English. When an
|
||||
English message with a US spelling is added, add its UK spelling there too.
|
||||
|
||||
## Coverage
|
||||
|
||||
A message a locale never received falls back to English silently, so a gap shows up only as a row
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
The UI layout in `crates/ui-egui/src/workspace.rs` maps the original engine registry placements into ribbon sections. `docs/features.md` continues to document registry placements; command registrations and ids are unchanged.
|
||||
|
||||
Always shown, in order: MODEL, SURFACE, ASSEMBLE, INSERT, INSPECT, MANAGE, VIEW, SHEET METAL. SKETCH appears during sketch editing. SHEET METAL is reachable in every document, so a sheet-metal part can start from a sketch or a solid; it takes the contextual style and selects itself when the selected body (or the last body of the active component) has evaluated sheet-metal data. Entering a context selects its tab; the other tabs remain available. RENDER belongs to the Render workspace.
|
||||
Always shown, in order: MODEL, SURFACE, ASSEMBLE, INSERT, INSPECT, MANAGE, VIEW. SKETCH appears during sketch editing; SHEET METAL appears for the selected body (or the last body of the active component) when it has evaluated sheet-metal data. Entering a new context selects its tab; the other tabs remain available. RENDER belongs to the Render workspace.
|
||||
|
||||
**Bold command ids are default promoted buttons.** Every listed command remains in the section menu. Saved user pins can add buttons, as before.
|
||||
|
||||
@@ -12,9 +12,7 @@ Always shown, in order: MODEL, SURFACE, ASSEMBLE, INSERT, INSPECT, MANAGE, VIEW,
|
||||
| MODEL | CREATE | **`solid.extrude`**, **`solid.revolve`**, **`solid.hole`**, `solid.sweep`, `solid.loft`, `solid.box`, `solid.cylinder`, `solid.sphere`, `solid.torus`, `solid.pipe`, `solid.bounding_solid`, `solid.thread`, `solid.boundary_fill`, `solid.coil`, `solid.rib`, `solid.web`, `solid.emboss`, `plastic.boss`, `plastic.lip`, `plastic.snap_fit`, `plastic.rest` |
|
||||
| MODEL | MODIFY | **`solid.fillet`**, **`solid.chamfer`**, **`solid.shell`**, **`solid.press_pull`**, `sheet.convert`, `solid.combine`, `solid.scale`, `solid.offset_face`, `solid.draft`, `solid.split_face`, `solid.split_body`, `solid.replace_face`, `solid.remove`, `timeline.delete`, `face.delete` |
|
||||
| MODEL | ARRANGE | **`solid.move`**, **`solid.mirror`**, **`solid.pattern.rectangular`**, `solid.align`, `solid.pattern.circular`, `solid.pattern.path` |
|
||||
| MODEL | CONFIGURE | **`parameters.change`**, **`config.table`**, `config.configure` |
|
||||
| MODEL | CONSTRUCT | **`construct.plane.offset`**, `construct.plane.at_angle`, `construct.axis.through_cylinder`, `construct.axis.normal_to_face`, `construct.axis.two_planes`, `construct.axis.two_points`, `construct.axis.edge`, `construct.point.vertex`, `construct.point.two_edges`, `construct.point.three_planes`, `construct.point.center`, `construct.point.edge_plane`, `construct.point.along_path`, `construct.plane.midplane`, `construct.plane.two_edges`, `construct.plane.three_points`, `construct.plane.tangent`, `construct.plane.along_path`, `construct.plane.perpendicular` |
|
||||
| SURFACE | SKETCH | **`sketch.create`** |
|
||||
| SURFACE | CREATE | **`surface.extrude`**, **`surface.revolve`**, **`surface.sweep`**, **`surface.loft`**, `surface.boundary`, `surface.patch`, `surface.offset`, `surface.ruled`, `surface.blend` |
|
||||
| SURFACE | EDIT | **`surface.trim`**, **`surface.untrim`**, **`surface.extend`**, **`surface.stitch`**, `surface.unstitch`, `surface.reverse_normal`, `surface.fair`, `surface.fillet`, `surface.match` |
|
||||
| SURFACE | CONVERT | **`surface.thicken`**, **`mesh.convert`** |
|
||||
@@ -46,13 +44,10 @@ Always shown, in order: MODEL, SURFACE, ASSEMBLE, INSERT, INSPECT, MANAGE, VIEW,
|
||||
| SKETCH | CONSTRAIN | **`sketch.dimension`**, **`sketch.constraint.horizontal_vertical`**, **`sketch.constraint.coincident`**, **`sketch.constraint.tangent`**, **`sketch.constraint.equal`**, **`sketch.constraint.parallel`**, **`sketch.constraint.perpendicular`**, `sketch.construction`, `sketch.constrainer`, `sketch.constraint.fix`, `sketch.constraint.midpoint`, `sketch.constraint.concentric`, `sketch.constraint.collinear`, `sketch.constraint.symmetry`, `sketch.constraint.curvature`, `sketch.constraint.polygon`, `sketch.auto_constrain`, `sketch.auto_constrain_from_datum` |
|
||||
| SKETCH | REFERENCE | **`sketch.project`**, `sketch.intersect`, `sketch.include_3d`, `sketch.project_to_surface`, `sketch.intersection_curve`, `sketch.spun_profile`, `sketch.isoparametric_curve`, `sketch.fit_curves_to_section`, `sketch.insert_dxf`, `sketch.insert_svg`, `canvas.insert` |
|
||||
| SKETCH | FINISH SKETCH | **`sketch.finish`**, `sketch.finish_auto_constrain` |
|
||||
| SHEET METAL | SKETCH | **`sketch.create`** |
|
||||
| SHEET METAL | CREATE | **`sheet.flange`**, **`sheet.hem`**, **`sheet.fold`**, **`sheet.perforate`**, `sheet.convert` |
|
||||
| SHEET METAL | FLAT | **`sheet.unfold`**, **`sheet.refold`**, **`sheet.flat_pattern`** |
|
||||
| SHEET METAL | OUTPUT | **`sheet.export_dxf`**, **`sheet.export_bend_table`** |
|
||||
| SHEET METAL | RULES | **`sheet.manage_rules`** |
|
||||
| SHEET METAL | CONFIGURE | **`parameters.change`**, **`config.table`**, `config.configure` |
|
||||
| SKETCH | CONFIGURE | **`parameters.change`**, **`config.table`**, `config.configure` |
|
||||
| RENDER | SCENE | **`render.scene`** |
|
||||
| RENDER | IMAGE | **`render.start`** |
|
||||
|
||||
@@ -68,7 +63,6 @@ Explicit command-id lists override the default placement mapping. Shared command
|
||||
| RENDER / IMAGE | RENDER / IMAGE | `render.start` |
|
||||
| RENDER / SCENE | RENDER / SCENE | `render.scene` |
|
||||
| SHEET METAL / CREATE | MODEL / MODIFY | `sheet.convert` |
|
||||
| SHEET METAL / CREATE | SHEET METAL / SKETCH | `sketch.create` |
|
||||
| SHEET METAL / CREATE | SHEET METAL / CREATE | `sheet.flange`, `sheet.perforate`, `sheet.hem`, `sheet.fold` |
|
||||
| SHEET METAL / CREATE | SHEET METAL / FLAT | `sheet.flat_pattern` |
|
||||
| SHEET METAL / MODIFY | MANAGE / RULES | `sheet.manage_rules` |
|
||||
@@ -132,7 +126,7 @@ Additional old panels used for shared layouts migrate as follows: SELECT on any
|
||||
|
||||
## Automation handles
|
||||
|
||||
The tab handle form stays `tab:<UPPERCASE NAME>`. Added: `tab:MODEL`, `tab:ASSEMBLE`, `tab:INSERT`, `tab:INSPECT`, `tab:MANAGE`, `tab:VIEW`. SURFACE and RENDER retain their names; SKETCH is available only in context; SHEET METAL is always available. Legacy aliases remain: `tab:SOLID` and `tab:PLASTIC` → MODEL; `tab:MESH` → SURFACE; `tab:UTILITIES` → MANAGE. The Home and document-tab handles are unchanged.
|
||||
The tab handle form stays `tab:<UPPERCASE NAME>`. Added: `tab:MODEL`, `tab:ASSEMBLE`, `tab:INSERT`, `tab:INSPECT`, `tab:MANAGE`, `tab:VIEW`. SURFACE and RENDER retain their names; SKETCH and SHEET METAL are available only in context. Legacy aliases remain: `tab:SOLID` and `tab:PLASTIC` → MODEL; `tab:MESH` → SURFACE; `tab:UTILITIES` → MANAGE. The Home and document-tab handles are unchanged.
|
||||
|
||||
Section labels retain `panel:<tab>:<section>` and collapsed sections retain `collapsed:<tab>:<section>`, with destinations from the tables above. In particular, `panel:SOLID:CREATE` becomes `panel:MODEL:CREATE`, selection-filter panels become `panel:VIEW:SELECT`, and `panel:SKETCH:CONSTRAINTS` becomes `panel:SKETCH:CONSTRAIN`. Command button and menu handles keep their command ids.
|
||||
|
||||
|
||||
+4
-4
@@ -10,7 +10,7 @@ SolidCraft reads STEP (ISO 10303-21; AP203, AP214 and AP242 geometry) with its o
|
||||
|
||||
Every import (STEP, IGES, 3MF, STL, OBJ; inserted, dropped, opened as a new design, or run as `file.insert_step`, `file.insert_mesh` or `doc.open` from a script, the CLI or MCP) becomes a **new component named after the file** (`bracket.step` → component `bracket`), placed in the active component at the file's origin. The Import feature belongs to it, so the file's bodies never land loose next to your own. Opening a file as a design makes the component too, so the browser shows the file's name. The command's reply reports it: `component` (id), `component_name` and `occurrence`.
|
||||
|
||||
A STEP **assembly** keeps its structure: each product under the file's root becomes a component nested under the import's, named after the product, at the place the file gives it. IGES groups and subfigures become nested components the same way. A part (or sub-assembly) the file places more than once becomes **one component with an occurrence per placement**: the Import feature builds the part once and skips the file's later copies (`skip` in the feature, format 22), and the occurrences show it everywhere else. Placements that are scaled, mirrored or otherwise non-rigid keep their geometry in place in the parent component. The reply adds `subcomponents` (how many components were made below the import's) and `rigid_joints`.
|
||||
A STEP **assembly** keeps its structure: each product under the file's root becomes a component nested under the import's, named after the product, at the place the file gives it. A part (or sub-assembly) the file places more than once becomes **one component with an occurrence per placement**: the Import feature builds the part once and skips the file's later copies (`skip` in the feature, format 22), and the occurrences show it everywhere else. The reply adds `subcomponents` (how many components were made below the import's) and `rigid_joints`.
|
||||
|
||||
The Browser reuses body, sketch and construction-plane membership, child lists and resolved placements while the
|
||||
camera moves. Large assemblies keep their tree open without resolving every part and
|
||||
@@ -34,7 +34,7 @@ The contents of an imported assembly are **rigid by default**: rigid joints (a r
|
||||
|
||||
Designs saved before imports made components keep their Import where it is (no component is made for it) and rebuild as they did.
|
||||
|
||||
Read: manifold solid breps (with voids), faceted breps, shell-based surface models; planes, cylinders, cones, spheres, tori, B-spline and rational B-spline surfaces (with knots, Bézier, uniform, quasi-uniform), surfaces of revolution and linear extrusion, trimmed surfaces; lines, circles, ellipses, hyperbolas and parabolas (as exact rational curves, which export writes back as exact rational B-splines), B-spline curves, polylines, trimmed/surface/seam curves; length and angle units (SI prefixes, conversion-based units such as inches); product names (meaningful solid names are kept, placeholders use part names; `names` below chooses); surface colours; assemblies (next-assembly-usage occurrences placed by item-defined transformations, and mapped items) — the product tree is kept in the feature and becomes the import's components (above). Files are untrusted: sizes, entity counts and nesting are capped and every kernel call is guarded. What cannot be read becomes a warning on the feature (a face left out gives an open body); not read yet: offset surfaces, pcurve-only edges.
|
||||
Read: manifold solid breps (with voids), faceted breps, shell-based surface models; planes, cylinders, cones, spheres, tori, B-spline and rational B-spline surfaces (with knots, Bézier, uniform, quasi-uniform), surfaces of revolution and linear extrusion, trimmed surfaces; lines, circles, ellipses, hyperbolas and parabolas (as exact rational curves, which export writes back as exact rational B-splines), B-spline curves, polylines, trimmed/surface/seam curves; length and angle units (SI prefixes, conversion-based units such as inches); product names (body names come from the solid's name, else the product's; `names` below chooses); surface colours; assemblies (next-assembly-usage occurrences placed by item-defined transformations, and mapped items) — the product tree is kept in the feature and becomes the import's components (above). Files are untrusted: sizes, entity counts and nesting are capped and every kernel call is guarded. What cannot be read becomes a warning on the feature (a face left out gives an open body); not read yet: offset surfaces, pcurve-only edges.
|
||||
|
||||
Extruded circular and elliptical faces keep their profile's parameter seam outside
|
||||
the face trim, or on an explicit seam edge. Narrow faces such as rounded gear tooth
|
||||
@@ -46,7 +46,7 @@ the supporting ellipse in the middle.
|
||||
Files from different systems differ in which way is up and in what they call their solids. `doc.open`, `file.insert_step` and the MCP `open` tool take two options for STEP and IGES files; without them a file comes in as written.
|
||||
|
||||
- **`up`**: `"z"` (the default) keeps the file's axes. Many systems write Y up, so such a part lies on its back in SolidCraft's Z-up space. `"up": "y"` turns the import's component a quarter turn about X (+90°: Y becomes Z), as the window's "Stand it up" offer does, so an assembly's parts and instances turn together. The import and the turn are one undo step, the reply names the turned occurrence as `stand_up`, and only the file's component turns, not what is already in the design. The window offers to stand a part up after a STEP file opens unless the call said which way is up (`up: "z"` as well as `"y"`).
|
||||
- **`names`**: `"auto"` (the default) keeps meaningful solid names and replaces placeholders such as `Body1` or `Body 2 (3)` with the nearest named product, then the occurrence name if no product is named. `"solid"` keeps the solid's name; `"product"` chooses the part's name; `"instance"` chooses the assembly occurrence (`Post-2`), falling back to the product. If the chosen name is missing, the solid's name remains. Repeated names are numbered (`Post`, `Post (2)`). Names are stored with the Import feature and survive reopening the design. Files without names or assembly metadata retain generated body names and a flat structure.
|
||||
- **`names`**: what the bodies are called. `"solid"` (the default) is the name of the solid in the file, and the product's name where the solid has none. Some systems fill a solid's name with the last feature that made it (`Cut-Extrude3`), so every body of an assembly has a name that says nothing about its part. `"product"` names each body after the product (the part) that holds it, and `"instance"` after the assembly occurrence (`Post-2`), or the product where the body is not in an occurrence. A name the file leaves out, or fills with a placeholder, falls back to the next one (instance, product, solid). Repeated names are numbered as any body names are (`Post`, `Post (2)`). The names are stored with the Import feature, so the design reopens with them. The default stays the solid's name because SolidCraft's own STEP export writes a body's name there.
|
||||
|
||||
```json
|
||||
{"command": "file.insert_step", "params": {"path": "frame.step", "up": "y", "names": "instance"}}
|
||||
@@ -61,7 +61,7 @@ display on the resulting body.
|
||||
|
||||
## IGES
|
||||
|
||||
IGES 5.3 files (`.igs`/`.iges`) open, insert and drop the same way: `crates/kernel/src/iges_in.rs` (written from the published specification) restates the file as STEP and the STEP reader reads it, so the feature holds STEP text. Read: manifold solid B-reps (186) with their shells, faces, loops, edge and vertex lists; trimmed (144) and bounded (143) surfaces, and bare B-spline patches, sewn within their owning group into a solid by their shared edges (an open body when they do not close); groups (402 forms 1, 7, 14 and 15), subfigure definitions (308) and instances (408), retaining names, nesting and placements; lines, circular arcs, ellipses, composite curves, rational B-spline curves; planes (108, 190), cylinders, cones, spheres, tori, rational B-spline surfaces, surfaces of revolution and tabulated cylinders; transformation matrices; units; colours (314 and the predefined numbers); body names (name properties, else labels). Not read yet: ruled and offset surfaces, curves on surfaces given only in parameter space. Export (`file.export` to `.igs`) writes each body as a manifold solid B-rep on the same surfaces a STEP export uses, with its name and colour.
|
||||
IGES 5.3 files (`.igs`/`.iges`) open, insert and drop the same way: `crates/kernel/src/iges_in.rs` (written from the published specification) restates the file as STEP and the STEP reader reads it, so the feature holds STEP text. Read: manifold solid B-reps (186) with their shells, faces, loops, edge and vertex lists; trimmed (144) and bounded (143) surfaces, and bare B-spline patches, sewn into a solid by their shared edges (an open body when they do not close); lines, circular arcs, ellipses, composite curves, rational B-spline curves; planes (108, 190), cylinders, cones, spheres, tori, rational B-spline surfaces, surfaces of revolution and tabulated cylinders; transformation matrices; units; colours (314 and the predefined numbers); body names (name properties, else labels). Not read yet: ruled and offset surfaces, curves on surfaces given only in parameter space. Export (`file.export` to `.igs`) writes each body as a manifold solid B-rep on the same surfaces a STEP export uses, with its name and colour.
|
||||
|
||||
## FreeCAD and Rhino
|
||||
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
{
|
||||
"description": "Issue #2040: a block with one side at 45 degrees, rounded by 3.8 mm fillets along the ends of its top and bottom. The slanted face's outline has four quarter-ellipses, which its sketch fits as splines; extruding the face as a cut or a join failed with 'boolean ... no result'. The extrude is added by the test.",
|
||||
"commands": [
|
||||
{"command": "sketch.create", "params": {"plane": "XZ", "flip": true}},
|
||||
{"command": "sketch.line", "params": {"points": [[0, 0], [11.514718625761429, 0], [20, 8.485281374238571], [0, 8.485281374238571]], "closed": true}},
|
||||
{"command": "sketch.finish", "params": {}},
|
||||
{"command": "solid.extrude", "params": {"distance": 10}},
|
||||
{"command": "solid.fillet", "params": {"edges": [[10, -10, 8.485281374238571], [10, 0, 8.485281374238571], [5.757359312880714, 0, 0], [5.757359312880714, -10, 0]], "radius": 3.8}}
|
||||
]
|
||||
}
|
||||
@@ -30,10 +30,10 @@ In `$SKILL/scripts/`:
|
||||
|
||||
## Traps
|
||||
|
||||
1. **Zero dimension.** A sketch dimension driven to 0 loses its side: the point it measures has no direction left, so the solver may leave it anywhere on the axis. On the next parameter change it either fails with `its constraints would conflict` (a point placed by dimensions from the origin) or, with no error, moves it: a slot that other constraints also held slides to the origin when the distance reaches 0 and, the solver taking the shortest step that fits, keeps the side it was drawn on when the value comes back. Check every distance expression against the whole allowed range of each parameter in it, counts included; the walk in step 3 catches the failure, and only the volume or the position catches a point that ended up on the other side. For a point on an axis, pass `x=None` or `y=None` to `place`: it aligns the point instead of dimensioning it. For a position that does reach 0, such as the first of a centred row of one, dimension it from a sketch point placed outside the part: a point at x = -100 mm, then the distance `100 mm - (n - 1) / 2 * pitch` from it.
|
||||
1. **Zero dimension.** A sketch dimension driven to 0 loses its side. On the next parameter change it either fails with `its constraints would conflict` (a point placed by dimensions from the origin) or, with no error, puts the point on either side (a slot that other constraints also held came back mirrored). Check every distance expression against the whole allowed range of each parameter in it, counts included; the walk in step 3 catches the failure, and only the volume or the position catches the mirror. For a point on an axis, pass `x=None` or `y=None` to `place`: it aligns the point instead of dimensioning it. For a position that does reach 0, such as the first of a centred row of one, dimension it from a sketch point placed outside the part: a point at x = -100 mm, then the distance `100 mm - (n - 1) / 2 * pitch` from it.
|
||||
2. **Counts.** Solid patterns take counts 1..1000; a count that reaches 0 fails the rebuild. A fractional count rounds to the nearest whole number without an error (6.5 gives 7 copies), while every other expression uses the exact value, so a centred row shifts. Nothing in SolidCraft enforces a parameter range during a parameter change (configuration rules apply only when a configuration row is activated): choose a range that keeps every count at 1 or more, write "whole number" and the range in the comment, and use `round(n)` wherever the count also positions something.
|
||||
3. **Circumscribed polygons.** `sketch.polygon.circumscribed` with a size dimension and one vertical side still has 1 dof: its corners can alternate in and out. `sketch.constraint.polygon` makes it regular; `scb.hexagon` adds it.
|
||||
4. **Boolean retries.** A `Boolean retry: ...` warning means the result may be wrong (see "Boolean warning" in the `solidcraft-modeling` reference), so check the volume of that state. `temporary coincident-face separation` comes from faces that coincide. A tapered tool whose start or end lies on a face of a plain block, or a straight cylinder joined onto the floor of a filleted, shelled box, does not log it; a `tool displacement` warning shows up when a join and a cut share one location, as in a standoff built as a joined cylinder with a cut pilot hole, patterned together. That case reports the warning but its volume agrees with the analytic growth, and a single ring profile removes the warning. Starting cutters about 1 mm past the faces they pierce and sinking joins about 1 mm into the body remain good practice on a single feature. Check the volume of every state either way.
|
||||
4. **Boolean retries.** A `Boolean retry: ...` warning means the result may be wrong (see "Boolean warning" in the `solidcraft-modeling` reference), so check the volume of that state. `temporary coincident-face separation` comes from faces that coincide. In a plain block, a tapered tool whose start or end lies on a face logs it and a straight one does not; on the floor of a filleted, shelled box, a straight cylinder joined onto the floor logs it too, and sunk 1 mm into the floor it does not. Starting cutters about 1 mm past the faces they pierce (sizes extrapolated along any taper) and sinking joins about 1 mm into the body remove the warning on a single feature. They did not fix standoffs built as a joined cylinder and a cut pilot hole, patterned together: those still kept material in the holes, and one ring profile fixed it ("Boolean warning" in the `solidcraft-modeling` reference). Check the volume of every state either way.
|
||||
5. **Measurement accuracy.** The `solidcraft-modeling` reference gives how far measured volumes stray from computed ones. Centre of mass and bounding box come out up to about 5e-5 of the part size off. Set test tolerances as the template says.
|
||||
6. **Expressions.** They have `+ - * / ^ %`, `sin cos tan asin acos atan atan2 sqrt abs min max floor ceil round mod trunc exp ln log log10 pow sign hypot` (`log` is base 10), `pi` and units; no `if` and no comparisons. Build steps from `floor`, `mod`, `min`, `max` and `sign`, which gives 1 at 0. `asin acos atan atan2` return angles, so a unitless parameter cannot hold them.
|
||||
7. **Snapping.** A point created exactly on an existing point or the origin becomes coincident with it (`connect` defaults to true).
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user